<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/themes/prism-tomorrow.min.css" rel="stylesheet" />
    <style>
        body {
            margin: 0;
            font-family: var(--vscode-font-family);
            color: var(--vscode-editor-foreground);
            background-color: var(--vscode-editor-background);
            overflow-x: hidden;
            /* 防止水平滚动 */
        }

        #chat-container {
            display: flex;
            flex-direction: column;
            height: 100vh;
            overflow-y: hidden;
            overflow-x: hidden;
            /* 防止水平滚动 */
            max-width: 100vw;
            /* 限制最大宽度 */
        }

        #messages {
            flex: 1 1 auto;
            overflow-y: auto;
            overflow-x: hidden;
            /* 防止水平滚动 */
            padding: 5px 15px;
            /* 增加左右内边距，确保对齐一致 */
            min-height: 200px;
            display: flex;
            flex-direction: column;
            width: 100%;
            /* 确保宽度不超过容器 */
            scroll-behavior: smooth;
            /* 平滑滚动效果 */
            box-sizing: border-box;
            /* 确保padding不影响总宽度 */
            padding-bottom: 10px;
        }

        .message {
            margin: 10px 0px;
            display: flex;
            flex-direction: column;
            max-width: 100%;
            word-wrap: break-word;
            /* 确保文本换行 */
            box-sizing: border-box;
            /* 确保子元素边距不超出 */
        }

        .message-header {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 8px;
        }

        .message-avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            overflow: hidden;
            flex-shrink: 0;
        }

        .message-avatar img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .message-name {
            font-size: 12px;
            color: rgba(255, 255, 255, 0.6);
        }

        .message-content {
            display: flex;
            align-items: flex-start;
            gap: 8px;
            width: 100%;
            max-width: 100%;
            /* 确保不超出容器 */
            padding-left: 0;
            /* 防止额外的左边距 */
            margin-left: 0;
            /* 确保没有额外的左边距 */
        }

        .message-bubble {
            padding: 12px 12px;
            border-radius: 6px;
            font-size: 13px;
            line-height: 1.5;
            word-wrap: break-word;
            overflow-wrap: break-word;
            max-width: calc(100% - 20px);
            /* 确保留有边距 */
            color: var(--vscode-editor-foreground);
            background: var(--vscode-editor-background);
            border: 1px solid var(--vscode-panel-border);
            height: auto;
            overflow: visible;
            /* 添加过渡效果减少抖动 */
            transition: all 0.2s ease;
            will-change: contents;
            /* 提示浏览器内容将会变化 */
            min-width: 100%;
            /* 统一消息气泡宽度 */
            box-sizing: border-box;
            /* 确保边框不会影响宽度计算 */
        }

        /* 专为工具调用消息优化的气泡样式 */
        .message-bubble:has(.tool-call-container:not(:empty)) {
            width: 100%;
            /* 使包含工具调用的气泡更宽 */
            max-width: 97%;
            /* 确保在移动设备上也能看到 */
            padding-top: 8px;
            /* 减少顶部内边距 */
            padding-bottom: 8px;
            /* 减少底部内边距 */
        }

        /* 特别优化"完成任务"工具标签 */
        .tool-call[data-tool-name="attempt_completion"] .tool-name,
        .tool-call:has(.tool-name:contains("完成任务")) .tool-name {
            color: var(--vscode-testing-iconPassed);
            /* 使用成功颜色 */
        }

        /* 减少Markdown格式消息中的过多空白 */
        .message-bubble p {
            margin: 0;
            /* 减少段落间距 */
        }

        .message-bubble ul,
        .message-bubble ol {
            margin: 0.5em 0;
            padding-left: 1.5em;
            /* 减少列表缩进 */
        }

        .message-bubble li {
            margin: 0.3em 0;
            /* 减少列表项间距 */
        }

        .message-bubble li+li {
            margin-top: 0.3em;
            /* 列表项之间的间距 */
        }

        .message-bubble h1,
        .message-bubble h2,
        .message-bubble h3,
        .message-bubble h4,
        .message-bubble h5,
        .message-bubble h6 {
            margin: 0.8em 0 0.5em 0;
            /* 减少标题与周围元素的间距 */
        }

        .message-bubble blockquote {
            margin: 0.5em 0;
            padding-left: 1em;
            border-left: 3px solid #555;
        }

        .message-bubble hr {
            margin: 0.8em 0;
        }

        .user-message {
            align-self: flex-end;
            margin-right: 0px;
            /* 添加右边距，使消息不靠右边界太近 */

        }

        .user-message .message-header {
            flex-direction: row-reverse;
            padding-right: 0px;
            /* 头像和名称右侧增加间距 */
        }

        .user-message .message-content {
            flex-direction: row-reverse;
        }

        .user-message .message-bubble {
            background: var(--vscode-editor-background);
            color: var(--vscode-editor-foreground);
            border: 1px solid var(--vscode-panel-border);
            margin-right: 8px;
            /* 气泡右侧增加间距 */
        }

        .bot-message {
            align-self: flex-start;
            margin-left: 0;
            width: 100%;
            /* 确保宽度一致 */
            box-sizing: border-box;
        }

        .bot-message .message-content {
            width: 100%;
            box-sizing: border-box;
            padding: 0;
            margin: 0;
        }

        .bot-message .message-bubble {
            background: var(--vscode-editor-background);
            color: var(--vscode-editor-foreground);
        }

        .no-avatar {
            margin-top: 0;
        }

        .no-avatar-content {
            margin-left: 40px;
            /* 与头像位置对齐 */
            padding-left: 0;
            /* 防止额外的内边距 */
            box-sizing: border-box;
        }

        .reasoning-message .message-bubble {
            background: rgba(60, 60, 60, 0.4);
            border-left: 3px solid var(--vscode-textLink-foreground);
            padding: 12px 16px;
            margin-left: 0;
            /* 确保没有额外的左边距 */
            width: 90%;
            /* 确保宽度与普通消息一致 */
            box-sizing: border-box;
            /* 确保padding不影响宽度计算 */
        }

        .reasoning-message .message-content {
            padding-left: 0;
            margin-left: 0;
        }

        .reasoning-content {
            white-space: pre-wrap;
            font-family: var(--vscode-editor-font-family);
            font-size: 0.9em;
            color: var(--vscode-descriptionForeground);
            margin: 8px 0 0 0;
            /* 顶部边距，避免与header太近 */
        }

        .reasoning-header {
            display: flex;
            align-items: center;
            padding: 0 0 5px 0;
            cursor: pointer;
            color: var(--vscode-textLink-foreground);
            font-size: 0.9em;
            margin: 0;
            /* 去掉可能的边距 */
        }

        .reasoning-header:hover {
            text-decoration: underline;
        }

        #input-container {
            display: flex;
            flex-direction: column;
            padding-right: 10px;
            padding-bottom: 10px;
            margin-bottom: 10px;
            padding-left: 2px;
            background: rgba(30, 30, 30, 0.95);
            position: sticky;
            bottom: 0;
            border-radius: 8px;
            border: 1px solid rgba(255, 255, 255, 0.1);
            z-index: 10;
        }

        .input-row {
            display: flex;
            gap: 8px;
        }

        #message-input {
            flex: 1;
            min-height: 20px;
            height: 20px;
            max-height: 200px;
            /* 增加最大高度 */
            padding: 8px;
            background: transparent;
            color: var(--vscode-input-foreground);
            border: none;
            border-radius: 4px;
            font-family: var(--vscode-font-family);
            font-size: var(--vscode-font-size);
            line-height: 1.4;
            outline: none;
            resize: none;
            overflow-y: auto;
            white-space: pre-wrap;
            /* 保留换行符 */
            word-wrap: break-word;
            /* 允许单词换行 */
        }

        #message-input::placeholder {
            color: rgba(255, 255, 255, 0.3);
        }

        .controls-row {
            display: flex;
            justify-content: flex-end;
            gap: 8px;
            margin-top: 8px;
        }

        #model-select {
            background: rgba(45, 45, 45, 0.8);
            color: var(--vscode-input-foreground);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 4px;
            padding: 6px 24px 6px 8px;
            font-size: 13px;
            cursor: pointer;
            appearance: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='rgba(255, 255, 255, 0.5)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
            background-repeat: no-repeat;
            background-position: right 6px center;
            background-size: 16px;
            min-width: 120px;
            height: 32px;
        }

        #mode-select {
            background: rgba(45, 45, 45, 0.8);
            color: var(--vscode-input-foreground);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 4px;
            padding: 6px 24px 6px 8px;
            font-size: 13px;
            cursor: pointer;
            appearance: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='rgba(255, 255, 255, 0.5)' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
            background-repeat: no-repeat;
            background-position: right 6px center;
            background-size: 16px;
            min-width: 120px;
            height: 32px;
        }

        .send-button {
            padding: 6px 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: rgba(30, 30, 30, 0.95);
            border: 1px solid rgba(255, 255, 255, 0.1);
            border-radius: 4px;
            cursor: pointer;
            color: var(--vscode-input-foreground);
            min-width: 32px;
            height: 32px;
            transition: all 0.2s;
        }

        .send-button:hover:not(:disabled) {
            background: rgba(45, 45, 45, 0.95);
            border-color: rgba(11, 106, 240, 0.671);
        }

        .send-button:disabled {
            opacity: 0.5;
            cursor: not-allowed;
        }

        .intro-section {
            display: flex;
            align-items: center;
            padding: 20px;
            gap: 12px;
            background: var(--vscode-editor-background);
        }

        .intro-section.hidden {
            display: none;
        }

        .intro-logo {
            width: 48px;
            /* 稍微增大logo尺寸 */
            height: 48px;
            border-radius: 50%;
            /* 添加圆形效果 */
        }

        .intro-text {
            color: var(--vscode-foreground);
            font-size: 12px;
            /* 增大字体大小 */
            font-weight: 500;
            /* 稍微加粗 */
        }

        .intro-text .greeting {
            font-size: 20px;
            /* 问候语更大字号 */
            margin-bottom: 12px;
        }

        .code-container {
            background: #1e1e1e;
            color: white;
            border-radius: 8px;
            margin: 8px 0;
            position: relative;
            overflow: hidden;
            display: flex;
            flex-direction: column;
            /* 添加过渡效果和GPU加速减少抖动 */
            transition: height 0.2s ease;
            transform: translateZ(0);
            min-height: 50px;
            /* 提供最小高度防止突然扩展 */
        }

        .code-header {
            display: none;
            /* 隐藏原有的header */
        }

        .language-label {
            position: absolute;
            top: 8px;
            right: 8px;
            background: rgba(60, 60, 60, 0.7);
            color: #ccc;
            border-radius: 4px;
            padding: 2px 8px;
            font-size: 12px;
            transition: all 0.2s;
            z-index: 5;
        }

        .language-label:hover {
            background: #3c3c3c;
            color: white;
            cursor: pointer;
        }

        .copy-btn {
            position: absolute;
            top: 8px;
            right: 8px;
            background: #3c3c3c;
            color: white;
            border: none;
            padding: 2px 8px;
            border-radius: 4px;
            cursor: pointer;
            transition: background 0.2s;
            font-size: 12px;
            display: none;
            z-index: 6;
        }

        .copy-btn:hover {
            background: #4d4d4d;
        }

        .copy-btn.copied {
            background: #38a169;
        }

        .code-content {
            padding: 12px;
            margin: 0;
            overflow-x: auto;
        }

        /* 修复pre标签的默认样式，去除多余空白 */
        .code-container pre {
            margin: 0;
            padding: 12px;
            padding-top: 8px;
            /* 减少顶部内边距 */
            overflow-x: auto;
        }

        /* 确保pre内的code没有额外padding */
        .code-container pre code {
            padding: 0;
        }

        /* 代理模式的进度条样式 */
        .progress-container {
            margin: 10px 0;
            width: 100%;
            background: var(--vscode-editor-background);
            border-radius: 4px;
            border: 1px solid var(--vscode-panel-border);
            padding: 8px;
        }

        .progress-info {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 5px;
        }

        .progress-icon {
            width: 18px;
            height: 18px;
            text-align: center;
            line-height: 18px;
            border-radius: 50%;
            font-size: 12px;
        }

        .progress-icon.system {
            background: var(--vscode-textLink-foreground);
            color: white;
        }

        .progress-icon.success {
            background: var(--vscode-testing-iconPassed);
            color: white;
        }

        .progress-icon.error {
            background: var(--vscode-errorForeground);
            color: white;
        }

        .progress-icon.warning {
            background: var(--vscode-editorWarning-foreground);
            color: white;
        }

        .progress-message {
            font-size: 12px;
            flex: 1;
        }

        /* 文件操作结果样式 */
        .file-result {
            display: flex;
            gap: 8px;
            padding: 8px;
            margin: 8px 0;
            background: var(--vscode-editor-background);
            border: 1px solid var(--vscode-panel-border);
            border-radius: 4px;
        }

        .file-result-icon {
            font-size: 18px;
        }

        .file-result-content {
            flex: 1;
        }

        .file-result-path {
            font-weight: bold;
            margin-bottom: 4px;
        }

        .file-result-status {
            font-size: 12px;
        }

        .file-result.success .file-result-status {
            color: var(--vscode-testing-iconPassed);
        }

        .file-result.error .file-result-status {
            color: var(--vscode-errorForeground);
        }

        .chat-controls {
            display: flex;
            padding: 10px;
            background-color: var(--vscode-editor-background);
            border-top: 1px solid var(--vscode-panel-border);
            box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
            z-index: 10;
        }

        .partial {
            opacity: 0.8;
        }

        /* 工具调用和混合内容相关样式 */
        .tool-call-container {
            margin-top: 5px;
            /* 减少上方留白 */
            display: flex;
            flex-direction: column;
            gap: 8px;
            /* 减少间隙 */
            width: 100%;
        }

        /* 工具调用块样式 */
        .tool-call {
            background: var(--vscode-editor-inactiveSelectionBackground);
            border-radius: 6px;
            padding: 10px 12px;
            /* 调整内边距，减少上下空间 */
            margin: 4px 0;
            /* 减少外边距 */
            border: 1px solid var(--vscode-panel-border);
            transition: all 0.2s ease;
        }

        .tool-header {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 6px;
            /* 减少下边距 */
        }

        .tool-icon {
            color: var(--vscode-textLink-foreground);
            font-size: 16px;
        }

        .tool-name {
            color: var(--vscode-textLink-foreground);
            font-weight: 600;
        }

        .tool-summary {
            color: var(--vscode-foreground);
            font-size: 13px;
            margin-top: 2px;
            /* 减少上边距 */
            padding: 4px 8px;
            background: var(--vscode-editor-background);
            border-radius: 4px;
        }

        .tool-params {
            color: var(--vscode-descriptionForeground);
            font-size: 12px;
            margin-top: 2px;
            /* 减少上边距 */
            padding: 4px 8px;
            background: var(--vscode-editor-background);
            border-radius: 4px;
            font-family: var(--vscode-editor-font-family);
        }

        .tool-params>div {
            margin: 2px 0;
        }

        /* 工具调用块悬停效果 */
        .tool-call:hover {
            background: var(--vscode-editor-selectionBackground);
        }

        /* 工具调用块在消息中的布局 */
        .message-bubble .tool-call {
            margin: 4px 0;
            /* 减少上下边距 */
        }

        .message-bubble .tool-call:first-child {
            margin-top: 0;
        }

        .message-bubble .tool-call:last-child {
            margin-bottom: 0;
        }

        .tool-status {
            font-size: 12px;
            color: var(--vscode-descriptionForeground);
            font-style: italic;
            margin-left: auto;
        }

        .tool-actions {
            display: flex;
            gap: 8px;
            margin-top: 8px;
            /* 减少上边距 */
        }

        .tool-approve {
            background: var(--vscode-button-background);
            color: var(--vscode-button-foreground);
            border: none;
            padding: 4px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.2s ease;
        }

        .tool-approve:hover {
            opacity: 0.9;
        }

        .tool-reject {
            background: var(--vscode-errorForeground);
            color: white;
            border: none;
            padding: 4px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.2s ease;
        }

        .tool-reject:hover {
            opacity: 0.9;
        }

        .tool-result {
            margin-top: 8px;
            /* 减少上边距 */
            border-top: 1px solid var(--vscode-panel-border);
            padding-top: 8px;
            /* 减少上内边距 */
        }

        .tool-success {
            color: var(--vscode-testing-iconPassed);
            margin-bottom: 6px;
            /* 减少下边距 */
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .tool-error {
            color: var(--vscode-errorForeground);
            margin-bottom: 6px;
            /* 减少下边距 */
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .result-content {
            padding: 8px;
            background: var(--vscode-editor-background);
            border-radius: 4px;
            white-space: pre-wrap;
            font-family: var(--vscode-editor-font-family);
            font-size: var(--vscode-editor-font-size);
            max-height: 250px;
            overflow-y: auto;
        }

        .code-preview {
            margin: 0;
            white-space: pre-wrap;
            overflow: hidden;
            font-family: var(--vscode-editor-font-family);
            font-size: var(--vscode-editor-font-size);
        }

        .feedback-input {
            display: flex;
            flex-direction: column;
            gap: 8px;
            width: 100%;
        }

        .feedback-input textarea {
            width: 100%;
            background: var(--vscode-input-background);
            border: 1px solid var(--vscode-input-border);
            color: var(--vscode-input-foreground);
            border-radius: 4px;
            padding: 8px;
            font-family: var(--vscode-font-family);
        }

        .feedback-input div {
            display: flex;
            gap: 8px;
        }

        /* 确保文本和工具调用之间有适当间距 */
        .message-text+.tool-call-container {
            margin-top: 8px;
            /* 减少文本后工具容器的上边距 */
            position: relative;
        }

        .message-text+.tool-call-container::before {
            content: '';
            display: block;
            height: 1px;
            background: var(--vscode-panel-border);
            margin: 4px 0;
            /* 减少分隔线上下边距 */
            opacity: 0.5;
        }

        /* 多工具调用之间有分隔 */
        .tool-call+.tool-call {
            margin-top: 8px;
            /* 减少工具间的间距 */
            border-top: 1px dashed var(--vscode-panel-border);
            padding-top: 8px;
            /* 减少上内边距 */
        }

        /* attempt_completion工具样式优化 */
        .tool-call[data-tool-name="attempt_completion"],
        .tool-call:has(.tool-name:contains("完成任务")) {
            background-color: rgba(0, 100, 0, 0.1);
            /* 使用淡绿色背景 */
            border-left: 3px solid var(--vscode-testing-iconPassed);
            /* 添加绿色边框 */
        }

        .tool-params {
            color: var(--vscode-descriptionForeground);
            font-size: 12px;
            margin-top: 4px;
            padding: 4px 8px;
            background: var(--vscode-editor-background);
            border-radius: 4px;
            font-family: var(--vscode-editor-font-family);
        }

        .tool-params>div {
            margin: 2px 0;
        }

        /* 工具调用块悬停效果 */
        .tool-call:hover {
            background: var(--vscode-editor-selectionBackground);
        }

        /* 工具调用块在消息中的布局 */
        .message-bubble .tool-call {
            margin: 8px 0;
        }

        .message-bubble .tool-call:first-child {
            margin-top: 0;
        }

        .message-bubble .tool-call:last-child {
            margin-bottom: 0;
        }

        .tool-status {
            font-size: 12px;
            color: var(--vscode-descriptionForeground);
            font-style: italic;
            margin-left: auto;
        }

        .tool-actions {
            display: flex;
            gap: 8px;
            margin-top: 12px;
        }

        .tool-approve {
            background: var(--vscode-button-background);
            color: var(--vscode-button-foreground);
            border: none;
            padding: 4px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.2s ease;
        }

        .tool-approve:hover {
            opacity: 0.9;
        }

        .tool-reject {
            background: var(--vscode-errorForeground);
            color: white;
            border: none;
            padding: 4px 12px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.2s ease;
        }

        .tool-reject:hover {
            opacity: 0.9;
        }

        .tool-result {
            margin-top: 12px;
            border-top: 1px solid var(--vscode-panel-border);
            padding-top: 12px;
        }

        .tool-success {
            color: var(--vscode-testing-iconPassed);
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .tool-error {
            color: var(--vscode-errorForeground);
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .result-content {
            padding: 8px;
            background: var(--vscode-editor-background);
            border-radius: 4px;
            white-space: pre-wrap;
            font-family: var(--vscode-editor-font-family);
            font-size: var(--vscode-editor-font-size);
            max-height: 250px;
            overflow-y: auto;
        }

        .code-preview {
            margin: 0;
            white-space: pre-wrap;
            overflow: hidden;
            font-family: var(--vscode-editor-font-family);
            font-size: var(--vscode-editor-font-size);
        }

        .feedback-input {
            display: flex;
            flex-direction: column;
            gap: 8px;
            width: 100%;
        }

        .feedback-input textarea {
            width: 100%;
            background: var(--vscode-input-background);
            border: 1px solid var(--vscode-input-border);
            color: var(--vscode-input-foreground);
            border-radius: 4px;
            padding: 8px;
            font-family: var(--vscode-font-family);
        }

        .feedback-input div {
            display: flex;
            gap: 8px;
        }

        /* 确保文本和工具调用之间有适当间距 */
        .message-text+.tool-call-container {
            margin-top: 16px;
            position: relative;
        }

        .message-text+.tool-call-container::before {
            content: '';
            display: block;
            height: 1px;
            background: var(--vscode-panel-border);
            margin: 8px 0;
            opacity: 0.5;
        }

        /* 多工具调用之间有分隔 */
        .tool-call+.tool-call {
            margin-top: 12px;
            border-top: 1px dashed var(--vscode-panel-border);
            padding-top: 12px;
        }

        /* 工具调用在流式传输时的动画效果 */
        .partial .tool-call {
            border-left: 3px solid var(--vscode-textLink-foreground);
            animation: pulse 2s infinite;
        }

        @keyframes pulse {
            0% {
                box-shadow: 0 0 0 0 rgba(0, 122, 255, 0.2);
            }

            70% {
                box-shadow: 0 0 0 5px rgba(0, 122, 255, 0);
            }

            100% {
                box-shadow: 0 0 0 0 rgba(0, 122, 255, 0);
            }
        }

        .toggle-container {
            display: flex;
            align-items: center;
        }

        .toggle-switch {
            position: relative;
            display: inline-flex;
            align-items: center;
            cursor: pointer;
            font-size: 12px;
        }

        .toggle-switch input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .toggle-slider {
            position: relative;
            display: inline-block;
            width: 32px;
            height: 16px;
            background-color: rgba(120, 120, 120, 0.6);
            border-radius: 16px;
            transition: .4s;
            margin-right: 6px;
        }

        .toggle-slider:before {
            position: absolute;
            content: "";
            height: 12px;
            width: 12px;
            left: 2px;
            bottom: 2px;
            background-color: white;
            border-radius: 50%;
            transition: .4s;
        }

        input:checked+.toggle-slider {
            background-color: var(--vscode-button-background);
        }

        input:checked+.toggle-slider:before {
            transform: translateX(16px);
        }

        .toggle-label {
            color: var(--vscode-foreground);
        }

        .user-approval-box {
            position: fixed;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            z-index: 9999;
            background: var(--vscode-editor-background);
            color: var(--vscode-editor-foreground);
            padding: 24px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
            border: 1px solid var(--vscode-panel-border);
            max-width: 90%;
            width: 400px;
            text-align: center;
        }

        .user-approval-box .title {
            font-size: 16px;
            margin-bottom: 16px;
            color: var(--vscode-foreground);
        }

        .user-approval-box .description {
            margin-bottom: 20px;
            color: var(--vscode-descriptionForeground);
            word-break: break-word;
        }

        .user-approval-box .buttons {
            display: flex;
            justify-content: center;
            gap: 12px;
        }

        .user-approval-box button {
            padding: 8px 16px;
            border-radius: 4px;
            border: none;
            cursor: pointer;
            font-size: 14px;
            transition: opacity 0.2s;
        }

        .user-approval-box .approve-btn {
            background: var(--vscode-button-background);
            color: var(--vscode-button-foreground);
        }

        .user-approval-box .reject-btn {
            background: var(--vscode-errorForeground);
            color: white;
        }

        .user-approval-box button:hover {
            opacity: 0.9;
        }

        .user-approval-box .overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 9998;
        }

        /* 添加选项对话框样式 */
        .options-dialog {
            position: fixed;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            z-index: 9999;
            background: var(--vscode-editor-background);
            color: var(--vscode-editor-foreground);
            padding: 24px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
            border: 1px solid var(--vscode-panel-border);
            max-width: 90%;
            width: 500px;
        }

        .options-dialog .title {
            font-size: 16px;
            margin-bottom: 16px;
            color: var(--vscode-foreground);
        }

        .options-dialog .options-list {
            margin: 20px 0;
        }

        .options-dialog .option-item {
            display: flex;
            align-items: center;
            padding: 10px;
            margin-bottom: 8px;
            border: 1px solid var(--vscode-panel-border);
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s;
        }

        .options-dialog .option-item:hover {
            background: var(--vscode-list-hoverBackground);
        }

        .options-dialog .option-item.selected {
            background: var(--vscode-list-activeSelectionBackground);
            color: var(--vscode-list-activeSelectionForeground);
        }

        .options-dialog .option-radio {
            margin-right: 10px;
            width: 16px;
            height: 16px;
            border: 2px solid var(--vscode-checkbox-border);
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }

        .options-dialog .option-item.selected .option-radio {
            border-color: var(--vscode-checkbox-selectBackground);
        }

        .options-dialog .option-item.selected .option-radio::after {
            content: '';
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background: var(--vscode-checkbox-selectBackground);
        }

        .options-dialog .option-label {
            flex: 1;
        }

        .options-dialog .actions {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }

        .options-dialog button {
            padding: 8px 16px;
            border-radius: 4px;
            border: none;
            cursor: pointer;
            font-size: 14px;
            transition: opacity 0.2s;
        }

        .options-dialog .confirm-btn {
            background: var(--vscode-button-background);
            color: var(--vscode-button-foreground);
        }

        .options-dialog .cancel-btn {
            background: var(--vscode-button-secondaryBackground);
            color: var(--vscode-button-secondaryForeground);
        }

        .options-dialog button:hover {
            opacity: 0.9;
        }

        .options-dialog .overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.5);
            z-index: 9998;
        }

        /* 添加@提及菜单相关样式 */
        .context-menu-container {
            position: absolute;
            bottom: calc(100% - 10px);
            left: 15px;
            right: 15px;
            overflow-x: hidden;
            z-index: 1000;
        }

        .context-menu {
            background-color: var(--vscode-dropdown-background);
            border: 1px solid var(--vscode-editorGroup-border);
            border-radius: 3px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.25);
            display: flex;
            flex-direction: column;
            max-height: 200px;
            overflow-y: auto;
        }

        .context-menu-option {
            padding: 8px 12px;
            display: flex;
            align-items: center;
            justify-content: space-between;
            border-bottom: 1px solid var(--vscode-editorGroup-border);
        }

        .context-menu-option.selected {
            background-color: var(--vscode-quickInputList-focusBackground);
            color: var(--vscode-quickInputList-focusForeground);
        }

        .context-menu-option:hover:not(.no-select) {
            background-color: var(--vscode-list-hoverBackground);
            cursor: pointer;
        }

        .context-menu-option.no-select {
            cursor: default;
            opacity: 0.7;
        }

        .context-menu-option-content {
            display: flex;
            align-items: center;
            flex: 1;
            min-width: 0;
            overflow: hidden;
        }

        .context-menu-icon {
            margin-right: 8px;
            flex-shrink: 0;
            font-size: 14px;
        }

        .context-menu-label {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .context-menu-description {
            font-size: 0.85em;
            opacity: 0.7;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .context-menu-arrow {
            font-size: 14px;
            flex-shrink: 0;
            margin-left: 8px;
        }

        .context-menu-loading {
            padding: 8px 12px;
            display: flex;
            align-items: center;
            gap: 8px;
            opacity: 0.7;
        }

        /* 路径显示相关样式 */
        .path-container {
            display: flex;
            align-items: center;
            overflow: hidden;
        }

        .path-prefix {
            flex-shrink: 0;
        }

        .path-content {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            direction: rtl;
            text-align: left;
        }

        /* 二级选项样式 */
        .git-option-content {
            display: flex;
            flex-direction: column;
            gap: 0;
        }

        /* @图标按钮样式 */
        .at-symbol-btn {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 24px;
            height: 24px;
            background: transparent;
            border: none;
            color: var(--vscode-descriptionForeground);
            font-size: 14px;
            border-radius: 4px;
            cursor: pointer;
            position: absolute;
            left: 8px;
            top: 6px;
            z-index: 5;
            transition: all 0.2s;
        }

        .at-symbol-btn:hover {
            background: rgba(255, 255, 255, 0.1);
            color: var(--vscode-foreground);
        }

        /* MCP图标按钮样式 */
        .mcp-symbol-btn {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 24px;
            height: 24px;
            background: transparent;
            border: none;
            color: var(--vscode-descriptionForeground);
            font-size: 14px;
            border-radius: 4px;
            cursor: pointer;
            position: absolute;
            /* left: 36px; 在@按钮右侧 */
            /* top: 6px; */
            /* 定位到底部 */
            left: 10px;
            /* 定位到左侧 */
            z-index: 11;
            /* 确保在其他元素之上 */
            transition: all 0.2s;
        }

        .mcp-symbol-btn:hover {
            background: rgba(255, 255, 255, 0.1);
            color: var(--vscode-foreground);
        }

        .mcp-symbol-btn.active {
            color: var(--vscode-button-foreground);
            background: var(--vscode-button-background);
        }

        /* 标签样式 */
        .mention-tag {
            display: inline-flex;
            align-items: center;
            background: var(--vscode-editor-inactiveSelectionBackground);
            color: var(--vscode-editor-foreground);
            border-radius: 4px;
            padding: 2px 6px;
            margin: 2px;
            font-size: 12px;
            max-width: 150px;
            overflow: hidden;
        }

        .mention-tag-text {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .mention-tag-remove {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-left: 4px;
            cursor: pointer;
            font-size: 10px;
            width: 14px;
            height: 14px;
            border-radius: 50%;
            background: transparent;
            transition: all 0.2s;
        }

        .mention-tag-remove:hover {
            background: rgba(255, 255, 255, 0.2);
        }

        /* 标签容器样式 */
        .tags-container {
            display: flex;
            flex-wrap: wrap;
            gap: 3px;
            padding: 3px 8px;
            padding-left: 38px;
            /* 为@图标留出空间 */
            min-height: 24px;
            position: relative;
            margin-bottom: 3px;
            width: 100%;
        }

        .code-actions button:hover {
            opacity: 0.9;
        }

        /* 选项样式 */
        .options-message {
            margin-top: -10px;
        }

        .options-bubble {
            background-color: var(--vscode-editor-background);
            border: 1px solid var(--vscode-panel-border);
            padding: 16px;
            margin-left: auto;
            margin-right: auto;
            max-width: 95%;
            margin-top: 13px;
        }

        .options-title {
            font-weight: 500;
            margin-bottom: 12px;
            color: var(--vscode-foreground);
        }

        .options-list {
            display: flex;
            flex-direction: column;
            gap: 8px;
            margin-bottom: 8px;
        }

        .option-item {
            display: flex;
            align-items: center;
            padding: 10px 14px;
            border-radius: 6px;
            background-color: var(--vscode-button-secondaryBackground);
            color: var(--vscode-button-secondaryForeground);
            border: 1px solid var(--vscode-button-border);
            cursor: pointer;
            transition: all 0.2s;
            font-weight: 500;
        }

        .option-item:hover {
            background-color: var(--vscode-button-hoverBackground);
            transform: translateY(-1px);
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
        }

        .option-item.selected {
            background-color: var(--vscode-button-background);
            color: var(--vscode-button-foreground);
            border-color: var(--vscode-focusBorder);
        }

        .option-radio {
            width: 16px;
            height: 16px;
            border-radius: 50%;
            border: 2px solid var(--vscode-checkbox-border);
            margin-right: 10px;
            position: relative;
            flex-shrink: 0;
        }

        .option-item.selected .option-radio:after {
            content: '';
            position: absolute;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: var(--vscode-checkbox-selectBackground);
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

        .option-label {
            flex: 1;
        }

        .option-result {
            margin-top: 12px;
            padding: 8px;
            background-color: var(--vscode-editorWidget-background);
            border-radius: 4px;
            font-style: italic;
            text-align: center;
            color: var(--vscode-editorWarning-foreground);
        }

        /* 文件变更列表样式 */
        #pending-changes {
            background: rgba(0, 0, 0, 0.2);
            padding: 8px;
            border-radius: 6px;
            margin-bottom: 10px;
            transition: all 0.3s ease;
            position: sticky;
            bottom: 72px;
            /* 位于输入框上方 */
            z-index: 10;
        }

        .changes-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            font-weight: bold;
            margin-bottom: 8px;
            padding-bottom: 6px;
            border-bottom: 1px solid var(--vscode-panel-border);
            cursor: pointer;
            /* 添加指针样式表示可点击 */
        }

        .changes-title {
            display: flex;
            align-items: center;
        }

        .changes-title:before {
            content: "▼";
            margin-right: 5px;
            transition: transform 0.3s;
            display: inline-block;
        }

        .changes-collapsed .changes-title:before {
            transform: rotate(-90deg);
        }

        .changes-actions {
            display: flex;
            gap: 8px;
        }

        .changes-button {
            background: var(--vscode-button-secondaryBackground);
            color: var(--vscode-button-secondaryForeground);
            border: none;
            padding: 2px 8px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }

        .changes-button:hover {
            opacity: 0.9;
        }

        #changes-list {
            display: flex;
            flex-direction: column;
            gap: 6px;
            max-height: 300px;
            overflow-y: auto;
            transition: max-height 0.3s ease, opacity 0.3s ease;
        }

        .changes-collapsed #changes-list {
            max-height: 0;
            overflow: hidden;
            opacity: 0;
            margin: 0;
            padding: 0;
        }

        .change-item {
            display: flex;
            align-items: center;
            background: var(--vscode-editor-inactiveSelectionBackground);
            border-radius: 4px;
            padding: 6px 8px;
            font-size: 13px;
            position: relative;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .change-item:hover {
            background: var(--vscode-editor-selectionBackground);
        }

        .change-path {
            flex: 1;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            margin-right: 8px;
        }

        .change-stats {
            display: flex;
            align-items: center;
            gap: 6px;
            padding: 2px 6px;
            background: rgba(30, 30, 30, 0.6);
            border-radius: 3px;
            font-size: 12px;
            margin-right: 8px;
        }

        .stats-added {
            color: #4CAF50;
            font-weight: bold;
        }

        .stats-removed {
            color: #F44336;
            font-weight: bold;
        }

        .change-operation {
            padding: 1px 6px;
            border-radius: 3px;
            font-size: 12px;
            margin-right: 8px;
        }

        .change-operation.write {
            background: var(--vscode-testing-iconPassed);
            color: white;
        }

        .change-operation.replace {
            background: var(--vscode-editorWarning-foreground);
            color: white;
        }

        .change-actions {
            display: flex;
            gap: 4px;
        }

        .change-accept {
            background: var(--vscode-testing-iconPassed);
            color: white;
            border: none;
            width: 20px;
            height: 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .change-reject {
            background: var(--vscode-errorForeground);
            color: white;
            border: none;
            width: 20px;
            height: 20px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .change-status {
            font-size: 12px;
            padding: 2px 6px;
            border-radius: 3px;
            margin-right: 8px;
        }

        .change-status.confirmed {
            background: var(--vscode-testing-iconPassed);
            color: white;
        }

        /* 完成任务工具特殊样式 */
        .tool-call[data-tool-name="完成任务"],
        .tool-call[data-tool-name="attempt_completion"] {
            background: rgba(0, 128, 0, 0.1);
            border: 1px solid rgba(0, 128, 0, 0.3);
        }

        .tool-tag {
            display: inline-flex;
            align-items: center;
            background-color: var(--vscode-editor-background);
            border: 1px solid var(--vscode-widget-border);
            border-radius: 4px;
            padding: 2px 6px;
            margin: 1px 0;
            font-size: 12px;
            color: var(--vscode-foreground);
            cursor: default;
            position: relative;
            max-width: 100%;
        }

        .tool-tag[data-tool-name="task_complete"] {
            background-color: rgba(73, 156, 84, 0.1);
            border-color: var(--vscode-debugIcon-startForeground);
        }

        .server-toggle.disable {
            background: var(--vscode-errorForeground);
        }

        .server-delete {
            background: var(--vscode-errorForeground);
        }

        .server-error {
            color: var(--vscode-errorForeground);
            margin-top: 10px;
            font-size: 12px;
        }

        /* MCP工具弹出窗口样式 */
        .mcp-tools-popup {
            position: absolute;
            bottom: 75px;
            left: 20px;
            width: 300px;
            max-height: 400px;
            background: var(--vscode-editor-background);
            border: 1px solid var(--vscode-panel-border);
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
            z-index: 100;
            overflow: hidden;
            display: flex;
            flex-direction: column;
        }

        .mcp-popup-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 10px 12px;
            border-bottom: 1px solid var(--vscode-panel-border);
            background: var(--vscode-editorWidget-background);
        }

        .mcp-popup-title {
            font-weight: bold;
            font-size: 14px;
        }

        .mcp-popup-actions {
            display: flex;
            gap: 6px;
        }

        .mcp-action-btn {
            background: transparent;
            border: none;
            border-radius: 4px;
            width: 24px;
            height: 24px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: background 0.2s;
        }

        .mcp-action-btn:hover {
            background: rgba(255, 255, 255, 0.1);
        }

        .mcp-servers-list {
            padding: 10px;
            border-bottom: 1px solid var(--vscode-panel-border);
            max-height: 150px;
            overflow-y: auto;
        }

        .mcp-server-item {
            display: flex;
            align-items: center;
            padding: 6px 8px;
            border-radius: 4px;
            margin-bottom: 6px;
            background: var(--vscode-editorWidget-background);
            position: relative;
            cursor: pointer;
            transition: background 0.2s ease;
        }

        .mcp-server-item:hover {
            background: var(--vscode-list-hoverBackground);
        }

        /* 服务器折叠/展开指示器 */
        .mcp-server-item:after {
            content: "▼";
            position: absolute;
            right: 30px; /* 留出滑块的空间 */
            font-size: 10px;
            color: var(--vscode-descriptionForeground);
            transition: transform 0.2s ease;
        }

        .mcp-server-item.collapsed:after {
            transform: rotate(-90deg);
        }

        .mcp-server-status {
            width: 8px;
            height: 8px;
            border-radius: 50%;
            margin-right: 8px;
            flex-shrink: 0;
        }

        .mcp-server-status.connected {
            background: var(--vscode-testing-iconPassed);
        }

        .mcp-server-status.connecting {
            background: var(--vscode-editorWarning-foreground);
        }

        .mcp-server-status.disconnected {
            background: var(--vscode-errorForeground);
        }

        .mcp-server-name {
            flex: 1;
            font-size: 13px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }

        /* 添加服务器操作区域样式 */
        .mcp-server-actions {
            display: flex;
            align-items: center;
            margin-left: auto;
            z-index: 2; /* 确保在指示器之上 */
        }

        /* 服务器启用/禁用滑块样式 */
        .mcp-server-toggle {
            position: relative;
            display: inline-block;
            width: 24px;
            height: 14px;
            margin-left: 5px;
        }

        .mcp-server-toggle input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        .mcp-server-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: var(--vscode-button-secondaryBackground);
            transition: .4s;
            border-radius: 14px;
        }

        .mcp-server-slider:before {
            position: absolute;
            content: "";
            height: 10px;
            width: 10px;
            left: 2px;
            bottom: 2px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }

        .mcp-server-toggle input:checked + .mcp-server-slider {
            background-color: var(--vscode-button-background);
        }

        .mcp-server-toggle input:focus + .mcp-server-slider {
            box-shadow: 0 0 1px var(--vscode-button-background);
        }

        .mcp-server-toggle input:checked + .mcp-server-slider:before {
            transform: translateX(10px);
        }

        .mcp-tools-list {
            padding: 0; /* 移除原有内边距 */
            flex: 1;
            overflow-y: auto;
            /* 添加平滑过渡效果 */
            transition: all 0.2s ease;
        }

        /* 服务器下工具组样式 */
        .mcp-tools-group {
            padding: 10px;
            margin-bottom: 8px;
            transition: max-height 0.3s ease, opacity 0.3s ease, padding 0.3s ease;
            max-height: 1000px; /* 设置较大高度以容纳所有工具 */
            opacity: 1;
            overflow: hidden;
        }

        .mcp-tools-group.collapsed {
            max-height: 0;
            opacity: 0;
            padding-top: 0;
            padding-bottom: 0;
            margin: 0;
        }

        .mcp-tools-group-title {
            font-size: 12px;
            font-weight: bold;
            margin-bottom: 6px;
            color: var(--vscode-descriptionForeground);
        }

        .mcp-tool-item {
            display: flex;
            align-items: flex-start;
            padding: 6px 8px;
            border-radius: 4px;
            margin-bottom: 4px;
            background: var(--vscode-editorWidget-background);
            cursor: pointer;
            transition: background 0.2s;
        }

        .mcp-tool-item:hover {
            background: var(--vscode-list-hoverBackground);
        }

        .mcp-tool-icon {
            width: 16px;
            margin-right: 8px;
            color: var(--vscode-textLink-foreground);
            flex-shrink: 0;
        }

        .mcp-tool-details {
            flex: 1;
        }

        .mcp-tool-name {
            font-size: 12px;
            font-weight: 500;
        }

        .mcp-tool-description {
            font-size: 11px;
            color: var(--vscode-descriptionForeground);
            margin-top: 2px;
        }

        .mcp-empty-message {
            padding: 20px;
            text-align: center;
            color: var(--vscode-descriptionForeground);
            font-style: italic;
        }

        .tools-title {
            font-size: 14px;
            font-weight: bold;
            margin-bottom: 10px;
            color: var(--vscode-foreground);
        }

        /* MCP工具相关样式 */
        .mcp-symbol-btn {
            background: transparent;
            border: none;
            border-radius: 50%;
            width: 32px;
            height: 32px;
            padding: 0;
            font-size: 16px;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.2s;
            margin-right: 4px;
            color: var(--vscode-textLink-foreground);
        }

        .mcp-symbol-btn:hover,
        .mcp-symbol-btn.active {
            background-color: var(--vscode-button-hoverBackground);
            color: var(--vscode-button-foreground);
        }

        /* MCP服务器折叠/展开功能 */
        .mcp-server-item {
            display: flex;
            align-items: center;
            padding: 6px 8px;
            border-radius: 4px;
            margin-bottom: 2px;
            background: var(--vscode-editorWidget-background);
            cursor: pointer;
            position: relative;
        }

        .mcp-server-item:after {
            content: "▼";
            position: absolute;
            right: 10px;
            font-size: 10px;
            color: var(--vscode-descriptionForeground);
            transition: transform 0.2s;
        }

        .mcp-server-item.collapsed:after {
            transform: rotate(-90deg);
        }

        .mcp-tools-group {
            margin-bottom: 10px;
            transition: max-height 0.3s ease, opacity 0.3s ease;
            max-height: 500px;
            opacity: 1;
            overflow: hidden;
        }

        .mcp-tools-group.collapsed {
            max-height: 0;
            opacity: 0;
            margin: 0;
        }

        /* MCP工具调用块样式 */
        .mcp-tool-call {
            background: rgba(61, 61, 255, 0.05);
            border-left: 3px solid var(--vscode-textLink-activeForeground);
        }

        .mcp-tool-call .tool-icon {
            color: var(--vscode-textLink-activeForeground);
        }

        .mcp-params-preview {
            font-size: 12px;
            margin-top: 4px;
            padding: 4px 8px;
            background: rgba(128, 128, 128, 0.1);
            border-radius: 4px;
            white-space: normal;
            word-break: break-all;
        }

        .mcp-result-message {
            margin-top: 10px;
            padding: 10px;
            border-radius: 4px;
            font-size: 14px;
            font-weight: bold;
        }

        .mcp-result-bubble {
            padding: 12px;
            width: 100%;
        }

        .mcp-result-bubble.success {
            background: rgba(0, 128, 0, 0.05);
            border-left: 3px solid var(--vscode-testing-iconPassed);
        }

        .mcp-result-bubble.error {
            background: rgba(128, 0, 0, 0.05);
            border-left: 3px solid var(--vscode-errorForeground);
        }

        .mcp-result-header {
            display: flex;
            align-items: center;
            font-weight: bold;
            margin-bottom: 8px;
            padding-bottom: 6px;
            border-bottom: 1px solid rgba(128, 128, 128, 0.2);
        }

        .mcp-result-icon {
            margin-right: 8px;
            font-size: 16px;
        }

        .mcp-result-content {
            margin-top: 8px;
            max-height: 300px;
            overflow-y: auto;
            font-family: var(--vscode-editor-font-family);
        }

        .mcp-result-json {
            background: rgba(0, 0, 0, 0.1);
            padding: 8px;
            border-radius: 4px;
            font-family: var(--vscode-editor-font-family);
            font-size: 12px;
            overflow-x: auto;
            white-space: pre;
            margin: 0;
        }

        .mcp-error-message {
            color: var(--vscode-errorForeground);
            padding: 8px;
            background: rgba(255, 0, 0, 0.05);
            border-radius: 4px;
        }

        .mcp-result-title {
            font-size: 16px;
            color: var(--vscode-foreground);
        }



        .result-label {
            font-weight: bold;
            margin-bottom: 5px;
        }

        .result-content {
            font-size: 12px;
            color: var(--vscode-descriptionForeground);
        }

        /* MCP管理界面样式 */
        #mcp-manager-container {
            font-family: var(--vscode-font-family);
            color: var(--vscode-foreground);
            padding: 20px;
        }

        #mcp-manager-container .container {
            margin: 0 auto;
        }

        #mcp-manager-container h1 {
            font-size: 1.5rem;
            margin-bottom: 1rem;
            color: var(--vscode-foreground);
        }

        #mcp-manager-container h2 {
            font-size: 1.2rem;
            margin: 1.5rem 0 0.5rem 0;
            color: var(--vscode-foreground);
        }

        #mcp-manager-container .actions {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
        }

        #mcp-manager-container .button {
            background-color: var(--vscode-button-background);
            color: var(--vscode-button-foreground);
            border: none;
            padding: 6px 14px;
            border-radius: 2px;
            cursor: pointer;
            font-size: 13px;
        }

        #mcp-manager-container .button:hover {
            background-color: var(--vscode-button-hoverBackground);
        }

        #mcp-manager-container .list {
            background-color: var(--vscode-editor-background);
            border: 1px solid var(--vscode-panel-border);
            border-radius: 3px;
            margin-top: 10px;
        }

        #mcp-manager-container .loading,
        #mcp-manager-container .empty-message {
            padding: 15px;
            text-align: center;
            color: var(--vscode-descriptionForeground);
        }

        /* 服务器项样式 */
        #mcp-manager-container .server-item {
            display: flex;
            align-items: center;
            padding: 10px 15px;
            border-bottom: 1px solid var(--vscode-panel-border);
            cursor: pointer;
        }

        #mcp-manager-container .server-item:last-child {
            border-bottom: none;
        }

        #mcp-manager-container .server-item:hover {
            background-color: var(--vscode-list-hoverBackground);
        }

        #mcp-manager-container .server-item.selected {
            background-color: var(--vscode-list-activeSelectionBackground);
            color: var(--vscode-list-activeSelectionForeground);
        }

        #mcp-manager-container .server-status {
            width: 12px;
            height: 12px;
            border-radius: 50%;
            margin-right: 10px;
        }

        #mcp-manager-container .server-status.connected {
            background-color: var(--vscode-testing-iconPassed, #73c991);
        }

        #mcp-manager-container .server-status.connecting {
            background-color: var(--vscode-notificationsWarningIcon-foreground, #cca700);
        }

        #mcp-manager-container .server-status.disconnected,
        #mcp-manager-container .server-status.disabled {
            /* 添加 disabled 状态样式 */
            background-color: var(--vscode-testing-iconErrored, #f14c4c);
        }

        /* 为禁用服务器添加视觉效果 */
        #mcp-manager-container .server-item.disabled {
            opacity: 0.6;
        }

        #mcp-manager-container .server-name {
            flex-grow: 1;
            font-weight: 500;
        }

        #mcp-manager-container .server-actions {
            display: flex;
            gap: 5px;
        }

        #mcp-manager-container .icon-button {
            background: transparent;
            border: none;
            cursor: pointer;
            padding: 2px 4px;
            font-size: 14px;
            opacity: 0.7;
        }

        #mcp-manager-container .icon-button:hover {
            opacity: 1;
        }

        /* 工具项样式 */
        #mcp-manager-container .tools-group-title {
            padding: 10px 15px;
            background-color: var(--vscode-titleBar-activeBackground);
            font-weight: 600;
            border-bottom: 1px solid var(--vscode-panel-border);
            display: flex;
            /* 使用Flex布局 */
            justify-content: space-between;
            /* 两端对齐 */
            align-items: center;
            /* 垂直居中 */
        }

        #mcp-manager-container .tool-item {
            display: flex;
            padding: 12px 15px;
            border-bottom: 1px solid var(--vscode-panel-border);
            cursor: pointer;
        }

        #mcp-manager-container .tool-item:last-child {
            border-bottom: none;
        }

        #mcp-manager-container .tool-item:hover {
            background-color: var(--vscode-list-hoverBackground);
            /* 添加悬浮背景色 */
        }

        #mcp-manager-container .tool-icon {
            margin-right: 10px;
            font-size: 16px;
        }

        #mcp-manager-container .tool-details {
            flex-grow: 1;
        }

        #mcp-manager-container .tool-name {
            font-weight: 500;
            margin-bottom: 5px;
        }

        #mcp-manager-container .tool-description {
            font-size: 12px;
            color: var(--vscode-descriptionForeground);
        }



        /* 添加相关CSS样式 */
        /* 在head的style标签内添加 */

        /* 添加到style标签中的正确位置 */
        .notification {
            position: fixed;
            bottom: 20px;
            right: 20px;
            padding: 12px 15px;
            border-radius: 4px;
            color: white;
            font-size: 14px;
            z-index: 10000;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
            transition: all 0.3s ease;
        }

        .notification-error {
            background-color: var(--vscode-errorForeground, #f14c4c);
        }

        .notification-success {
            background-color: var(--vscode-testing-iconPassed, #73c991);
        }

        .notification-info {
            background-color: var(--vscode-textLink-foreground, #3794ff);
        }

        .notification-warning {
            background-color: var(--vscode-editorWarning-foreground, #cca700);
        }

        .notification-hide {
            opacity: 0;
            transform: translateY(10px);
        }

        /* 添加服务器滑块开关样式 */
        #mcp-manager-container .server-toggle {
            position: relative;
            display: inline-block;
            width: 40px;
            height: 20px;
            margin-right: 10px;
        }

        #mcp-manager-container .server-toggle input {
            opacity: 0;
            width: 0;
            height: 0;
        }

        #mcp-manager-container .server-slider {
            position: absolute;
            cursor: pointer;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: var(--vscode-button-secondaryBackground);
            transition: .4s;
            border-radius: 20px;
        }

        #mcp-manager-container .server-slider:before {
            position: absolute;
            content: "";
            height: 16px;
            width: 16px;
            left: 2px;
            bottom: 2px;
            background-color: white;
            transition: .4s;
            border-radius: 50%;
        }

        #mcp-manager-container .server-toggle input:checked+.server-slider {
            background-color: var(--vscode-button-background);
        }

        #mcp-manager-container .server-toggle input:focus+.server-slider {
            box-shadow: 0 0 1px var(--vscode-button-background);
        }

        #mcp-manager-container .server-toggle input:checked+.server-slider:before {
            transform: translateX(20px);
        }

        /* 工具参数悬浮提示样式 */
        #mcp-manager-container .tool-params-tooltip {
            position: absolute;
            display: none;
            /* 默认隐藏 */
            background-color: var(--vscode-editorWidget-background);
            border: 1px solid var(--vscode-widget-border);
            border-radius: 4px;
            padding: 10px;
            z-index: 10;
            max-width: 400px;
            min-width: 200px;
            /* 增加最小宽度 */
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
            bottom: 100%;
            /* 定位到父元素上方 */
            left: 50%;
            /* 水平居中 */
            transform: translateX(-50%);
            /* 精确水平居中 */
            margin-bottom: 5px;
            /* 与父元素留出间距 */
            white-space: normal;
            /* 允许换行 */
        }

        #mcp-manager-container .tool-item {
            position: relative;
            /* 父元素需要相对定位 */
            display: flex;
            /* 确保内部元素布局 */
            align-items: center;
            /* 垂直居中 */
        }

        #mcp-manager-container .tool-item:hover .tool-params-tooltip {
            display: block;
            /* 悬浮时显示 */
        }

        #mcp-manager-container .param-item {
            margin-bottom: 6px;
            font-size: 12px;
        }

        #mcp-manager-container .param-name {
            font-weight: bold;
            margin-right: 4px;
        }

        #mcp-manager-container .param-type {
            color: var(--vscode-textPreformat-foreground);
            font-style: italic;
        }

        #mcp-manager-container .param-description {
            margin-top: 2px;
            color: var(--vscode-descriptionForeground);
        }

        #mcp-manager-container .param-required {
            color: var(--vscode-errorForeground);
            font-size: 11px;
            margin-top: 2px;
        }

        /* 工具自动同意开关样式 */
        #mcp-manager-container .tool-auto-approve {
            display: flex;
            align-items: center;
            margin-left: auto;
            padding-left: 10px;
            min-width: 60px;
        }

        #mcp-manager-container .tool-auto-approve.enabled {
            color: var(--vscode-testing-iconPassed);
        }

        #mcp-manager-container .tool-auto-approve.disabled {
            color: var(--vscode-errorForeground);
        }

        #mcp-manager-container .tools-controls {
            display: flex;
            gap: 10px;
        }

        #mcp-manager-container .button.small {
            font-size: 12px;
            padding: 4px 8px;
        }

        /* MCP工具组相关样式 */
        .mcp-tools-group {
            margin-bottom: 10px;
            transition: max-height 0.2s ease, opacity 0.15s ease;
            max-height: 1000px;
            opacity: 1;
            overflow: hidden;
            border-left: 3px solid transparent;
        }

        .mcp-tools-group.collapsed {
            max-height: 0;
            opacity: 0;
            margin: 0;
            padding: 0;
            pointer-events: none;
        }

        /* MCP服务器项折叠/展开指示器 */
        .mcp-server-item {
            position: relative;
            transition: background-color 0.2s ease;
        }

        .mcp-server-item:after {
            content: "▼";
            position: absolute;
            right: 40px;
            font-size: 10px;
            color: var(--vscode-descriptionForeground);
            transition: transform 0.2s ease;
        }

        .mcp-server-item.collapsed:after {
            transform: rotate(-90deg);
        }

        /* 当前选中服务器样式 */
        .mcp-server-item:not(.collapsed) {
            background-color: var(--vscode-list-activeSelectionBackground);
            color: var(--vscode-list-activeSelectionForeground);
        }
    </style>
</head>

<body>
    <div id="chat-container">
        <div class="intro-section" id="introSection">
            <img src="BOT_AVATAR_PATH" alt="Logo" class="intro-logo">
            <div class="intro-text">
                <div class="greeting">Hi~ 我是星野编程小助手 👋</div>
                <div>我支持 解释代码、生成注释、代码补全等功能,你可以从 <a href="http://121.37.235.251:7000/#/home">功能向导</a> 了解详解,或是 <a
                        href="http://121.37.235.251:7000/#/message">提交反馈</a> 让我变得更好。</div>
            </div>
        </div>
        <div id="messages"></div>

        <!-- 添加文件变更列表 -->
        <div id="pending-changes" class="pending-changes-container" style="display: none;">
            <div class="changes-header">
                <span class="changes-title">待确认的文件变更</span>
                <div class="changes-actions">
                    <button id="accept-all-changes" class="changes-button">全部接受</button>
                    <button id="reject-all-changes" class="changes-button">全部拒绝</button>
                </div>
            </div>
            <div id="changes-list" class="changes-list"></div>
        </div>

        <div id="input-container">
            <div class="tags-container" id="tags-container">
                <button id="at-symbol-btn" class="at-symbol-btn">@</button>
            </div>
            <div class="input-row">
                <textarea id="message-input" placeholder="输入提示词...(shift+enter)换行" rows="1"></textarea>
                <button id="send-button" class="send-button">➤</button>
                <button id="stop-button" class="send-button" style="display: none;">⏸️</button>
            </div>
            <div class="controls-row">
                <button id="mcp-symbol-btn" class="mcp-symbol-btn" title="显示MCP工具">⚙️</button>
                <select id="model-select">
                    <option value="deepseek-r1">DeepSeek</option>
                    <option value="qwen3-235b-a22b">Qwen3</option>
                    <option value="qwen-turbo">Qwen-Turbo</option>
                    <option value="qwen-plus-latest">Qwen-Plus</option>
                </select>
                <select id="mode-select">
                    <option value="normal">普通对话</option>
                    <option value="agent">代理模式</option>
                </select>
                <div class="toggle-container">
                    <label class="toggle-switch">
                        <input type="checkbox" id="enable-reasoning-toggle" checked>
                        <span class="toggle-slider"></span>
                        <span class="toggle-label">深度思考</span>
                    </label>
                </div>
            </div>
        </div>
    </div>

    <!-- MCP管理界面容器 -->
    <div id="mcp-manager-container" style="display: none;  overflow-y: auto;">
        <div class="container">
            <h1>MCP服务器管理</h1>

            <div class="actions">
                <button id="add-server" class="button">添加服务器</button>
                <button id="refresh" class="button">刷新</button>
                <button id="open-mcp-settings" class="button">打开MCP设置</button>
                <button id="back-to-chat" class="button">返回聊天</button>
            </div>

            <div class="servers-container">
                <h2>已连接的MCP服务器</h2>
                <div id="servers-list" class="list">
                    <div class="loading">正在加载...</div>
                </div>
            </div>

            <div class="tools-container">
                <h2>可用的MCP工具</h2>
                <div id="tools-list" class="list">
                    <div class="loading">选择服务器查看工具</div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/prism.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-javascript.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-python.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-c.min.js"> </script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.24.1/components/prism-java.min.js"> </script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/4.3.0/marked.min.js"></script>

    <!-- 选项对话框 -->
    <div id="options-dialog" class="options-dialog" style="display: none;">
        <div id="options-overlay" class="overlay"></div>
        <div class="title" id="options-title">请选择一个选项</div>
        <div class="options-list" id="options-list">
            <!-- 选项将在JavaScript中动态添加 -->
        </div>
        <div class="actions">
            <button class="confirm-btn" id="options-confirm-btn" disabled>确认</button>
            <button class="cancel-btn" id="options-cancel-btn">取消</button>
        </div>
    </div>

    <!-- MCP工具弹出窗口 -->
    <div id="mcp-tools-popup" class="mcp-tools-popup" style="display: none;">
        <div class="mcp-popup-header">
            <div class="mcp-popup-title">MCP 工具</div>
            <div class="mcp-popup-actions">
                <button id="mcp-settings-btn" class="mcp-action-btn" title="MCP设置">⚙️</button>
                <button id="mcp-close-btn" class="mcp-action-btn" title="关闭">✖</button>
            </div>
        </div>
        <div class="mcp-servers-list" id="mcp-servers-list">
            <!-- 服务器列表将在JavaScript中动态添加 -->
        </div>
        <div class="mcp-tools-list" id="mcp-tools-list">
            <!-- 工具列表将在JavaScript中动态添加 -->
        </div>
    </div>

    <script>
        // VS Code的API实例
        const vscode = acquireVsCodeApi();

        // 保存消息历史记录
        let messagesState = [];
        let botMessageInProgress = false;
        let botMessageContent = '';
        let currentModeIsAgent = false;

        // 自动滚动标志
        let shouldAutoScroll = true;

        // 控制是否显示思考过程
        let enableReasoning = true;

        // 定义消息块引用，初始为null
        let currentMessageBlock = null;
        let currentReasoningBlock = null;
        // 跟踪当前会话是否已显示思考过程
        let currentSessionHasReasoning = false;

        // 获取DOM元素
        const messagesDiv = document.getElementById('messages');
        const messageInput = document.getElementById('message-input');
        const sendButton = document.getElementById('send-button');
        const stopButton = document.getElementById('stop-button');
        const modelSelect = document.getElementById('model-select');
        const modeSelect = document.getElementById('mode-select');

        // 记录上次发送的消息和时间
        let lastSentMessage = '';
        let lastSentTime = 0;

        // 初始化UI
        function initUI() {
            // 尝试加载已保存的状态
            const savedState = vscode.getState();
            if (savedState && savedState.messages) {
                messagesState = savedState.messages;
                renderMessages();
            }

            console.log('savedState', savedState)
            // 如果状态中有思考开关状态，则恢复
            if (savedState && savedState.enableReasoning !== undefined) {
                enableReasoning = savedState.enableReasoning;
                document.getElementById('enable-reasoning-toggle').checked = enableReasoning;
            }

            // 监听消息输入
            messageInput.addEventListener('keydown', (e) => {
                if (e.key === 'Enter') {
                    if (e.shiftKey) {
                        // Shift+Enter: 插入换行符
                        const start = messageInput.selectionStart;
                        const end = messageInput.selectionEnd;
                        const value = messageInput.value;
                        messageInput.value = value.substring(0, start) + '\n' + value.substring(end);
                        messageInput.selectionStart = messageInput.selectionEnd = start + 1;

                        // 调整输入框高度
                        messageInput.style.height = 'auto';
                        messageInput.style.height = Math.min(messageInput.scrollHeight, 200) + 'px';

                        e.preventDefault();
                    } else {
                        // 普通Enter: 发送消息
                        e.preventDefault();
                        sendMessage();
                    }
                }

                // 调整输入框高度
                setTimeout(() => {
                    messageInput.style.height = 'auto';
                    messageInput.style.height = Math.min(messageInput.scrollHeight, 200) + 'px';
                }, 0);
            });

            // 添加输入事件监听器，处理粘贴等其他输入情况
            messageInput.addEventListener('input', () => {
                messageInput.style.height = 'auto';
                messageInput.style.height = Math.min(messageInput.scrollHeight, 200) + 'px';
            });

            // 监听发送按钮
            sendButton.addEventListener('click', sendMessage);

            // 监听停止按钮
            stopButton.addEventListener('click', () => {
                stopGeneration();
                toggleInputControls(false);
            });

            // 初始化模式
            modeSelect.addEventListener('change', () => {
                currentModeIsAgent = modeSelect.value === 'agent';
            });

            // 监听思考开关
            setTimeout(() => {
                const toggle = document.getElementById('enable-reasoning-toggle');
                if (toggle) {
                    toggle.addEventListener('change', (e) => {
                        enableReasoning = e.target.checked;
                        console.log('改变思考开关', enableReasoning);
                        saveStateToExtension();
                    });
                } else {
                    console.error('找不到深度思考开关元素');
                }
            }, 1000);

            // 滚动到底部（自动滚动实现）
            scrollToBottomIfNeeded();

            // 保存当前状态给VS Code扩展
            saveStateToExtension();

            // 添加文件变更区域收缩功能
            const changesHeader = document.querySelector('.changes-header');
            if (changesHeader) {
                changesHeader.addEventListener('click', (e) => {
                    // 排除按钮点击
                    if (e.target.closest('.changes-actions')) return;

                    const container = document.getElementById('pending-changes');
                    container.classList.toggle('changes-collapsed');
                });
            }
        }

        // 保存状态到VS Code扩展
        function saveStateToExtension() {
            // 创建一个新的消息数组，使用原始文本
            const messagesForExtension = messagesState.map(msg => ({
                ...msg,
                text: msg.originalText || msg.text // 使用原始文本，如果没有则使用显示文本
            }));

            // 保存状态到WebView
            vscode.setState({
                messages: messagesState,
                currentModelValue: modelSelect.value,
                currentModeValue: modeSelect.value,
                enableReasoning: enableReasoning
            });

            // 发送给扩展时使用原始文本
            vscode.postMessage({
                command: 'saveState',
                state: {
                    messages: messagesForExtension,
                    currentModelValue: modelSelect.value,
                    currentModeValue: modeSelect.value,
                    enableReasoning: enableReasoning
                }
            });
        }
        // 发送消息
        function sendMessage() {
            const inputElement = document.getElementById('message-input');
            const text = inputElement.value.trim();

            // 如果消息为空，不发送
            if (!text) return;

            // 防止重复发送：检查是否与上次发送的消息相同，且时间间隔小于2秒
            const now = Date.now();
            if (text === lastSentMessage && now - lastSentTime < 2000) {
                console.log('防止重复发送', text);
                return;
            }

            // 更新上次发送的消息和时间
            lastSentMessage = text;
            lastSentTime = now;

            // 清空输入框
            inputElement.value = '';

            // 添加用户消息到界面
            addUserMessage(text);
            console.log('enableReasoning', enableReasoning)
            // 发送到扩展
            vscode.postMessage({
                command: 'sendMessage',
                text: text,
                mode: modeSelect.value,
                model: modelSelect.value,
                enableReasoning: enableReasoning
            });

            // 设置输入控件状态
            toggleInputControls(true);

            // 设置机器人消息状态
            botMessageInProgress = true;

            // 重置会话状态
            resetSessionState();
        }

        // 停止生成
        function stopGeneration() {
            vscode.postMessage({
                command: 'stopGeneration'
            });
            botMessageInProgress = false;
            toggleInputControls(false);
        }

        // 添加用户消息
        function addUserMessage(text) {
            // 隐藏介绍部分
            document.getElementById('introSection').classList.add('hidden');

            const message = {
                sender: 'user',
                text: text
            };
            messagesState.push(message);
            vscode.setState({ messages: messagesState });
            renderMessage(message, messagesState.length - 1);
            scrollToBottomIfNeeded();

            // 保存状态
            saveStateToExtension();
        }

        // 添加机器人消息
        function addBotMessage(text) {
            // 隐藏介绍部分
            document.getElementById('introSection').classList.add('hidden');

            botMessageInProgress = true;
            botMessageContent = text;
            const message = {
                sender: 'bot',
                text: text
            };
            messagesState.push(message);
            vscode.setState({ messages: messagesState });

            // 根据是否有思考过程决定是否显示头像
            if (currentSessionHasReasoning) {
                renderMessageWithoutAvatar(message, messagesState.length - 1);
            } else {
                renderMessage(message, messagesState.length - 1);
            }

            // 设置当前消息块引用
            currentMessageBlock = document.querySelector(`.message-bubble[data-index="${messagesState.length - 1}"]`);

            scrollToBottomIfNeeded();

            // 保存状态
            saveStateToExtension();
        }

        // 渲染没有头像的消息
        function renderMessageWithoutAvatar(message, index) {
            const messageEl = document.createElement('div');
            messageEl.className = `message ${message.sender}-message no-avatar`;
            messageEl.setAttribute('data-index', index);

            // 消息内容
            const contentEl = document.createElement('div');
            contentEl.className = 'message-content no-avatar-content';

            const bubbleEl = document.createElement('div');
            bubbleEl.className = 'message-bubble';
            bubbleEl.setAttribute('data-index', index);

            // 根据发送者处理消息内容
            if (message.sender === 'user') {
                bubbleEl.textContent = message.text;
            } else {
                // 使用marked解析markdown
                bubbleEl.innerHTML = formatBotMessage(message.text);

                // 高亮代码块，使用requestAnimationFrame减少布局抖动
                if (message.text && message.text.includes('```')) {
                    requestAnimationFrame(() => {
                        Prism.highlightAllUnder(bubbleEl);
                    });
                }
            }

            contentEl.appendChild(bubbleEl);
            messageEl.appendChild(contentEl);

            // 添加到消息容器
            messagesDiv.appendChild(messageEl);
        }

        // 创建推理块函数
        function createReasoningBlock(initialText) {

            const reasoningBlock = document.createElement('div');
            reasoningBlock.className = 'message bot-message reasoning-message';
            if (!currentSessionHasReasoning) {
                // 创建消息头部（添加头像和昵称）
                const headerEl = document.createElement('div');
                headerEl.className = 'message-header';

                // 头像
                const avatarEl = document.createElement('div');
                avatarEl.className = 'message-avatar';
                const avatarImg = document.createElement('img');
                avatarImg.src = 'BOT_AVATAR_PATH';
                avatarEl.appendChild(avatarImg);
                headerEl.appendChild(avatarEl);

                // 名称
                const nameEl = document.createElement('div');
                nameEl.className = 'message-name';
                nameEl.textContent = '星野';
                headerEl.appendChild(nameEl);

                reasoningBlock.appendChild(headerEl);
            }
            // 创建消息内容容器
            const contentEl = document.createElement('div');
            contentEl.className = 'message-content';

            const bubbleEl = document.createElement('div');
            bubbleEl.className = 'message-bubble reasoning-bubble';

            // 添加可折叠标题
            const reasoningHeader = document.createElement('div');
            reasoningHeader.className = 'reasoning-header';
            reasoningHeader.textContent = '思考过程 (点击展开/折叠)';
            reasoningHeader.addEventListener('click', () => {
                const content = reasoningHeader.nextElementSibling;
                content.style.display = content.style.display === 'none' ? 'block' : 'none';
            });
            bubbleEl.appendChild(reasoningHeader);

            // 推理内容
            const reasoningContent = document.createElement('div');
            reasoningContent.className = 'reasoning-content';
            reasoningContent.textContent = initialText || '';
            reasoningContent.style.display = 'block'; // 默认展开

            bubbleEl.appendChild(reasoningContent);
            contentEl.appendChild(bubbleEl);
            reasoningBlock.appendChild(contentEl);

            return reasoningBlock;
        }

        // 重置会话状态
        function resetSessionState() {
            currentMessageBlock = null;
            currentReasoningBlock = null;
            currentSessionHasReasoning = false;
            botMessageInProgress = false;
        }

        // 更新最后一条机器人消息
        function updateLastBotMessage(text) {
            if (messagesState.length === 0) return;

            const lastMessageIndex = messagesState.length - 1;
            const lastMessage = messagesState[lastMessageIndex];

            if (lastMessage.sender === 'bot') {
                // 保存原始消息到状态中
                lastMessage.originalText = text;

                // 创建用于显示的格式化文本
                let displayText = text;

                // 匹配普通工具标签，转换为块状显示
                const toolTagRegex = /<(list_files|read_file|write_to_file|search_files|execute_command|replace_in_file|create_directory|delete_file|rename_file|attempt_completion)>([\s\S]*?)<\/\1>/g;

                displayText = displayText.replace(toolTagRegex, (match, toolName, content) => {
                    // 获取工具的显示名称
                    const displayName = getToolDisplayName(toolName);

                    // 创建工具调用块
                    let blockContent = `<div class="tool-call" data-tool-name="${toolName}">
                        <div class="tool-header">
                            <span class="tool-icon">🔧</span>
                            <span class="tool-name">${displayName}</span>
                        </div>`;

                    // 提取关键参数
                    const params = {};
                    const paramRegex = /<([a-zA-Z_]+)>([\s\S]*?)<\/\1>/g;
                    let paramMatch;
                    while ((paramMatch = paramRegex.exec(content)) !== null) {
                        params[paramMatch[1]] = paramMatch[2].trim();
                    }

                    // 根据工具类型显示不同的内容
                    switch (toolName) {
                        case 'attempt_completion':
                            if (params.summary) {
                                blockContent += `<div class="tool-summary">📝 ${params.summary}</div>`;
                            }
                            break;
                        case 'write_to_file':
                        case 'read_file':
                        case 'delete_file':
                            if (params.path) {
                                blockContent += `<div class="tool-params">📁 文件: ${params.path}</div>`;
                            }
                            break;
                        case 'execute_command':
                            if (params.command) {
                                blockContent += `<div class="tool-params">⌨️ 命令: ${params.command}</div>`;
                            }
                            break;
                        case 'search_files':
                            if (params.pattern) {
                                blockContent += `<div class="tool-params">🔍 搜索: ${params.pattern}</div>`;
                            }
                            break;
                        default:
                            // 显示所有参数的简要信息
                            if (Object.keys(params).length > 0) {
                                blockContent += '<div class="tool-params">';
                                for (const [key, value] of Object.entries(params)) {
                                    if (key !== 'content' && value.length < 50) {
                                        blockContent += `<div>${key}: ${value}</div>`;
                                    }
                                }
                                blockContent += '</div>';
                            }
                    }

                    blockContent += '</div>';
                    return blockContent;
                });

                // 匹配MCP工具标签，转换为块状显示
                const mcpToolRegex = /<mcp-tool\s+server="([^"]+)"\s+tool="([^"]+)"\s+params=(\{[^}]+\})><\/mcp-tool>/g;

                displayText = displayText.replace(mcpToolRegex, (match, serverName, toolName, paramsStr) => {
                    // 解析参数
                    let params = {};
                    try {
                        params = JSON.parse(paramsStr);
                    } catch (e) {
                        console.error('解析MCP工具参数失败:', e);
                    }

                    // 创建MCP工具调用块
                    let blockContent = `<div class="tool-call mcp-tool-call">
                        <div class="tool-header">
                            <span class="tool-icon">⚡</span>
                            <span class="tool-name">${serverName}.${toolName}</span>
                        </div>
                        <div class="tool-params">
                            <div>服务器: ${serverName}</div>
                            <div>工具: ${toolName}</div>`;

                    // 显示参数信息
                    if (Object.keys(params).length > 0) {
                        blockContent += `<div class="mcp-params-preview">参数: `;
                        try {
                            // 简化参数显示，最多显示3个参数
                            const entries = Object.entries(params);
                            const previewEntries = entries.slice(0, 3);
                            blockContent += previewEntries.map(([k, v]) =>
                                `${k}: ${typeof v === 'string' ? v : JSON.stringify(v).substring(0, 30)}`
                            ).join(', ');

                            if (entries.length > 3) {
                                blockContent += ` ...等${entries.length - 3}个参数`;
                            }
                        } catch (e) {
                            blockContent += JSON.stringify(params).substring(0, 50) + '...';
                        }
                        blockContent += `</div>`;
                    }

                    blockContent += `</div></div>`;
                    return blockContent;
                });

                // 去除多余的空行
                displayText = displayText.replace(/\n{3,}/g, '\n\n');

                // 更新显示内容
                lastMessage.displayText = displayText;

                // 更新状态
                vscode.setState({ messages: messagesState });

                // 更新显示
                updateMessageContent(lastMessageIndex, displayText);
                scrollToBottomIfNeeded();

                // 保存状态
                saveStateToExtension();
            }
        }

        // 获取工具显示名称
        function getToolDisplayName(toolName) {
            const displayNames = {
                'write_to_file': '写入文件',
                'read_file': '读取文件',
                'replace_in_file': '替换文件内容',
                'search_files': '搜索文件',
                'list_files': '列出文件',
                'execute_command': '执行命令',
                'create_directory': '创建目录',
                'delete_file': '删除文件',
                'rename_file': '重命名文件',
                'attempt_completion': '完成任务'
            };
            return displayNames[toolName] || toolName;
        }

        // 添加进度更新消息
        function addProgressUpdate(type, message) {
            // 创建或获取进度容器
            let progressContainer = document.querySelector('.progress-container');
            if (!progressContainer) {
                progressContainer = document.createElement('div');
                progressContainer.className = 'progress-container';
                messagesDiv.appendChild(progressContainer);
            }

            // 创建进度信息
            const progressInfo = document.createElement('div');
            progressInfo.className = 'progress-info';

            // 图标
            const icon = document.createElement('div');
            icon.className = `progress-icon ${type}`;

            // 基于类型设置图标内容
            switch (type) {
                case 'system': icon.textContent = 'i'; break;
                case 'success': icon.textContent = '✓'; break;
                case 'error': icon.textContent = '!'; break;
                case 'warning': icon.textContent = '⚠'; break;
                default: icon.textContent = '•';
            }

            progressInfo.appendChild(icon);

            // 消息
            const messageEl = document.createElement('div');
            messageEl.className = 'progress-message';
            messageEl.textContent = message;
            progressInfo.appendChild(messageEl);

            // 添加到进度容器
            progressContainer.appendChild(progressInfo);

            // 滚动到底部（自动滚动实现）
            scrollToBottomIfNeeded();
        }

        // 添加文件操作结果
        function addFileResult(success, path, error) {
            // 创建文件结果元素
            const fileResult = document.createElement('div');
            fileResult.className = `file-result ${success ? 'success' : 'error'}`;

            // 图标
            const icon = document.createElement('div');
            icon.className = 'file-result-icon';
            icon.textContent = success ? '📄' : '❌';
            fileResult.appendChild(icon);

            // 内容
            const content = document.createElement('div');
            content.className = 'file-result-content';

            // 文件路径
            const pathEl = document.createElement('div');
            pathEl.className = 'file-result-path';
            pathEl.textContent = path || '未知路径';
            content.appendChild(pathEl);

            // 状态
            const status = document.createElement('div');
            status.className = 'file-result-status';
            status.textContent = success ? '文件创建成功' : `错误: ${error || '未知错误'}`;
            content.appendChild(status);

            fileResult.appendChild(content);

            // 添加到消息容器
            messagesDiv.appendChild(fileResult);

            // 滚动到底部（自动滚动实现）
            scrollToBottomIfNeeded();
        }

        // 渲染所有消息
        function renderMessages() {
            messagesDiv.innerHTML = '';

            if (messagesState.length > 0) {
                // 有消息，隐藏介绍部分
                document.getElementById('introSection').classList.add('hidden');
                messagesState.forEach((message, index) => {
                    renderMessage(message, index);
                });
            } else {
                // 没有消息，显示介绍部分
                document.getElementById('introSection').classList.remove('hidden');
            }
        }

        // 渲染单个消息
        function renderMessage(message, index) {
            const messageEl = document.createElement('div');
            messageEl.className = `message ${message.sender}-message`;
            messageEl.setAttribute('data-index', index);

            // 消息头部
            const headerEl = document.createElement('div');
            headerEl.className = 'message-header';

            // 头像
            const avatarEl = document.createElement('div');
            avatarEl.className = 'message-avatar';
            const avatarImg = document.createElement('img');
            avatarImg.src = message.sender === 'user' ? 'USER_AVATAR_PATH' : 'BOT_AVATAR_PATH';
            avatarEl.appendChild(avatarImg);
            headerEl.appendChild(avatarEl);

            // 名称
            const nameEl = document.createElement('div');
            nameEl.className = 'message-name';
            nameEl.textContent = message.sender === 'user' ? '你' : '星野';
            headerEl.appendChild(nameEl);

            messageEl.appendChild(headerEl);

            // 消息内容
            const contentEl = document.createElement('div');
            contentEl.className = 'message-content';

            const bubbleEl = document.createElement('div');
            bubbleEl.className = 'message-bubble';
            bubbleEl.setAttribute('data-index', index);

            // 根据发送者处理消息内容
            if (message.sender === 'user') {
                bubbleEl.innerHTML = formatBotMessage(message.text);
                if (message.text && message.text.includes('```')) {
                    requestAnimationFrame(() => {
                        Prism.highlightAllUnder(bubbleEl);
                    });
                }
            } else {
                // 使用displayText进行显示，如果没有则使用text
                const displayContent = message.displayText || message.text;
                bubbleEl.innerHTML = formatBotMessage(displayContent);

                // 高亮代码块
                if (displayContent && displayContent.includes('```')) {
                    requestAnimationFrame(() => {
                        Prism.highlightAllUnder(bubbleEl);
                    });
                }
            }

            contentEl.appendChild(bubbleEl);
            messageEl.appendChild(contentEl);

            // 添加到消息容器
            messagesDiv.appendChild(messageEl);
        }

        // 更新消息内容
        function updateMessageContent(index, text) {
            const bubbleEl = document.querySelector(`.message-bubble[data-index="${index}"]`);
            if (bubbleEl) {
                // 保存滚动位置
                const scrollPosition = messagesDiv.scrollTop;
                const wasAtBottom = (messagesDiv.scrollHeight - messagesDiv.scrollTop) <= (messagesDiv.clientHeight + 50);

                // 更新内容
                bubbleEl.innerHTML = formatBotMessage(text);

                // 使用requestAnimationFrame平滑处理高亮和滚动
                if (text && text.includes('```')) {
                    requestAnimationFrame(() => {
                        Prism.highlightAllUnder(bubbleEl);

                        // 如果之前在底部，则保持在底部
                        if (wasAtBottom) {
                            scrollToBottomIfNeeded();
                        } else {
                            messagesDiv.scrollTop = scrollPosition;
                        }
                    });
                } else {
                    // 如果之前在底部，则保持在底部
                    if (wasAtBottom) {
                        scrollToBottomIfNeeded();
                    } else {
                        messagesDiv.scrollTop = scrollPosition;
                    }
                }
            }
        }

        // 格式化机器人消息
        function formatBotMessage(text) {
            if (!text) return '';

            try {
                // 确保marked已定义
                if (typeof marked === 'undefined') {
                    return `<p>${text}</p>`;
                }

                // 配置marked选项，减少空白
                marked.setOptions({
                    gfm: true,
                    breaks: true,
                    sanitize: false,
                    smartypants: false
                });

                // 使用marked解析markdown
                let htmlContent = marked.parse(text);

                // 处理代码块，添加复制按钮
                htmlContent = htmlContent.replace(/<pre><code class="language-(\w+)">([\s\S]*?)<\/code><\/pre>/g, (match, lang, code) => {
                    // 确保语言是支持的
                    const supportedLangs = ['javascript', 'typescript', 'python', 'css', 'html', 'json', 'jsx', 'java', 'c', 'cpp'];
                    const language = supportedLangs.includes(lang) ? lang : 'javascript';
                    const languageText = language.charAt(0).toUpperCase() + language.slice(1);

                    // 新的代码块结构 - 移动语言标签到代码区域顶部
                    return `<div class="code-container" onmouseover="showCopyButton(this)" onmouseout="hideCopyButton(this)">
                        <span class="language-label">${languageText}</span>
                        <button class="copy-btn" onclick="copyCode(this)">复制</button>
                        <pre><code class="language-${language}">${code}</code></pre>
                    </div>`;
                });

                return htmlContent;
            } catch (e) {
                console.error('格式化消息错误:', e);
                // 如果解析出错，返回原始文本
                return `<p>${text}</p>`;
            }
        }

        // 显示复制按钮
        function showCopyButton(container) {
            const languageLabel = container.querySelector('.language-label');
            const copyBtn = container.querySelector('.copy-btn');

            if (languageLabel) languageLabel.style.display = 'none';
            if (copyBtn) copyBtn.style.display = 'block';
        }

        // 隐藏复制按钮
        function hideCopyButton(container) {
            const languageLabel = container.querySelector('.language-label');
            const copyBtn = container.querySelector('.copy-btn');

            // 如果按钮没有"已复制"类，则显示语言标签
            if (copyBtn && !copyBtn.classList.contains('copied')) {
                if (languageLabel) languageLabel.style.display = 'block';
                copyBtn.style.display = 'none';
            }
        }

        // 复制代码函数
        function copyCode(button) {
            const codeContainer = button.closest('.code-container');
            const code = codeContainer.querySelector('code').textContent;
            const languageLabel = codeContainer.querySelector('.language-label');

            navigator.clipboard.writeText(code).then(() => {
                // 修改按钮样式以指示复制成功
                button.textContent = '已复制';
                button.classList.add('copied');

                // 2秒后恢复按钮原样和语言标签
                setTimeout(() => {
                    button.textContent = '复制';
                    button.classList.remove('copied');

                    // 鼠标不在容器上时才显示语言标签
                    if (!codeContainer.matches(':hover')) {
                        button.style.display = 'none';
                        if (languageLabel) languageLabel.style.display = 'block';
                    }
                }, 2000);
            }).catch(err => {
                console.error('复制失败:', err);
                button.textContent = '复制失败';

                setTimeout(() => {
                    button.textContent = '复制';

                    // 鼠标不在容器上时才显示语言标签
                    if (!codeContainer.matches(':hover')) {
                        button.style.display = 'none';
                        if (languageLabel) languageLabel.style.display = 'block';
                    }
                }, 2000);
            });
        }

        // 监听来自扩展的消息
        window.addEventListener('message', event => {
            const message = event.data;
            console.log('收到消息:', message);

            switch (message.command) {
                case 'receiveThinking':
                    // 处理思考过程内容

                    if (!enableReasoning) break; // 如果禁用了思考过程，则不处理

                    if (message.text) {
                        addOrUpdateReasoning(message.text, currentReasoningBlock === null);
                    }
                    break;
                case 'thinkingEnd':
                    // 处理思考过程结束
                    if (currentReasoningBlock !== null) {
                        currentReasoningBlock = null;
                    }
                    currentMessageBlock = null;
                    break;

                case 'receiveMessage':
                    // 处理正常消息内容
                    if (message.text) {
                        if (currentMessageBlock === null) {
                            // 首次接收消息，创建新的消息块
                            botMessageInProgress = true;
                            botMessageContent = message.text;
                            addBotMessage(botMessageContent);
                        } else {
                            // 已有消息块，追加内容
                            botMessageContent += message.text;
                            updateLastBotMessage(botMessageContent);
                        }
                    }

                    // 如果是最后一条消息，恢复输入控件状态并重置块引用
                    if (message.isFinal) {
                        botMessageInProgress = false;
                        toggleInputControls(false);
                        // 重置会话状态
                        resetSessionState();
                    }
                    break;


                case 'endMessage':
                    // 结束消息生成
                    botMessageInProgress = false;
                    toggleInputControls(false);

                    // 重置会话状态
                    resetSessionState();

                    // 检查当前是否存在空消息，如果有则移除
                    if (botMessageContent === '' && messagesState.length > 0) {
                        // 获取最后一条消息
                        const lastMsg = messagesState[messagesState.length - 1];

                        // 如果是空的机器人消息，则删除
                        if (lastMsg.sender === 'bot' && (!lastMsg.text || lastMsg.text.trim() === '')) {
                            // 从DOM中移除
                            const lastMsgEl = document.querySelector(`.message[data-index="${messagesState.length - 1}"]`);
                            if (lastMsgEl) {
                                lastMsgEl.remove();
                            }

                            // 从状态中移除
                            messagesState.pop();
                            vscode.setState({ messages: messagesState });

                            // 保存更新后的状态
                            saveStateToExtension();
                        }
                    }
                    break;

                case 'progressUpdate':
                    // 添加进度更新
                    addProgressUpdate(message.type, message.message);

                    // 根据进度类型决定输入框状态
                    if (currentModeIsAgent) {
                        if (message.type === 'system' &&
                            (message.message === '正在思考下一步操作...' ||
                                message.message === '正在分析任务...' ||
                                message.message === '开始处理任务...' ||
                                message.message === '正在制定执行计划...')) {
                            toggleInputControls(true); // 锁定输入框
                        } else if (message.message === '任务完成' ||
                            message.message === '分析完成' ||
                            message.type === 'success' ||
                            message.type === 'error') {
                            toggleInputControls(false); // 完成或失败时解锁
                        }
                    }
                    break;

                case 'fileCreated':
                    // 添加文件创建结果
                    addFileResult(message.success, message.path, message.error);
                    // 不立即解锁，等待任务完成
                    break;

                case 'agentError':
                    // 添加代理错误
                    addProgressUpdate('error', `代理错误: ${message.error}`);
                    toggleInputControls(false);
                    break;

                case 'receiveError':
                    // 添加通信错误
                    addProgressUpdate('error', `通信错误: ${message.error}`);
                    toggleInputControls(false);
                    break;

                case 'restoreState':
                    // 从扩展恢复状态
                    if (message.state && message.state.messages) {
                        messagesState = message.state.messages;
                        renderMessages();

                        // 恢复模型和模式选择
                        if (message.state.currentModelValue) {
                            modelSelect.value = message.state.currentModelValue;
                        }
                        if (message.state.currentModeValue) {
                            modeSelect.value = message.state.currentModeValue;
                            currentModeIsAgent = modeSelect.value === 'agent';
                        }
                    }
                    break;

                case 'clearContext':
                    // 清除UI上的消息
                    messagesState = [];
                    vscode.setState({ messages: [] });
                    messagesDiv.innerHTML = '';

                    // 重置会话状态
                    resetSessionState();
                    botMessageContent = '';

                    // 重置所有文件变更
                    resetFileChanges();

                    // 显示介绍部分
                    document.getElementById('introSection').classList.remove('hidden');

                    // 添加系统消息提示
                    // 重置输入框
                    messageInput.value = '';
                    messageInput.style.height = 'auto';
                    messageInput.focus();

                    // 保存清除后的状态
                    saveStateToExtension();
                    break;
                case 'sendMsg':
                    addUserMessage(message.text)
                    vscode.postMessage({
                        command: 'sendMessage',
                        text: message.text,
                        mode: message.mode ? message.mode : modeSelect.value,
                        model: modelSelect.value,
                        enableReasoning: enableReasoning
                    });

                    // 设置输入控件状态
                    toggleInputControls(true);

                    // 设置机器人消息状态
                    botMessageInProgress = true;

                    // 重置会话状态
                    resetSessionState();
                    break;
                case 'partialMessage':
                    handlePartialMessage(message);
                    break;

                case 'toolResult':
                    // 处理工具结果消息
                    if (message.toolId) {
                        handleToolResult(message);
                    }
                    break;

                case 'mcpToolResult':
                    // 处理MCP工具执行结果
                    currentMessageBlock = null;
                    currentSessionHasReasoning = true;
                    handleMcpToolResult(message);
                    break;

                case 'requestToolApproval':
                    // 处理工具批准请求
                    break;

                case 'addToInput':
                    // 将内容添加到输入框
                    if (message.text) {
                        const messageInput = document.getElementById('message-input');
                        if (messageInput) {
                            // 如果输入框已有内容，添加换行
                            if (messageInput.value) {
                                messageInput.value += '\n';
                            }
                            messageInput.value += message.text;
                            // 调整输入框高度
                            messageInput.style.height = 'auto';
                            messageInput.style.height = messageInput.scrollHeight + 'px';
                            // 聚焦输入框
                            messageInput.focus();
                        }
                    }
                    break;

                case 'userApproval':
                    showUserApproval(message.toolName, message.params, message.path);
                    break;

                case 'showOptions':
                    currentMessageBlock = null;
                    currentReasoningBlock = null;
                    currentSessionHasReasoning = true;
                    // 处理显示选项
                    showOptionsDialog(message.message, message.options);
                    break;

                case 'action':
                    if (message.action === 'hideChat') {
                        // 隐藏聊天界面
                        document.getElementById('chat-container').style.display = 'none';
                    } else if (message.action === 'showChat') {
                        // 显示聊天界面
                        document.getElementById('chat-container').style.display = 'flex';
                    } else if (message.action === 'showMcpManager') {
                        // 显示MCP管理界面
                        closeMcpToolsPopup();
                        switchToMcpManager();
                    } else if (message.action === 'showChatView') {
                        // 返回聊天界面
                        switchToChatView();
                    }
                    break;
                case 'hideChat':
                    // 隐藏聊天界面
                    document.getElementById('chat-container').style.display = 'none';
                    break;

                case 'showChat':
                    // 显示聊天界面
                    document.getElementById('chat-container').style.display = 'flex';
                    break;
                default:
                    console.log('Unhandled message:', message);
                    break;
            }
        });

        // 切换输入控件
        function toggleInputControls(generating) {
            if (generating) {
                sendButton.style.display = 'none';
                stopButton.style.display = 'inline-block';
                messageInput.disabled = true;
                modelSelect.disabled = true;
                modeSelect.disabled = true;
            } else {
                sendButton.style.display = 'inline-block';
                stopButton.style.display = 'none';
                messageInput.disabled = false;
                modelSelect.disabled = false;
                modeSelect.disabled = false;

                // 重新聚焦输入框
                messageInput.focus();
            }
        }


        // 渲染混合内容（文本和工具调用）
        function renderMixedContent(messageElement, parsedContent, messageId, isPartial) {
            // 获取文本容器和工具调用容器
            const contentElement = messageElement.querySelector('.message-text');
            const toolContainer = messageElement.querySelector('.tool-call-container');

            // 显示文本内容
            if (parsedContent.textContent && parsedContent.textContent.length > 0) {
                contentElement.style.display = 'block';
                // 将文本片段合并并转换为HTML
                const textHtml = markdownToHtml(parsedContent.textContent.join(' '));
                contentElement.innerHTML = textHtml;
                highlightCode(contentElement);
            } else {
                // 没有文本内容时隐藏
                contentElement.style.display = 'none';
            }

            // 显示工具调用
            if (parsedContent.hasTools) {
                toolContainer.style.display = 'block';
                toolContainer.dataset.toolId = messageId;
                toolContainer.innerHTML = ''; // 清空现有内容

                // 为每个工具调用创建UI
                parsedContent.toolCalls.forEach((tool, index) => {
                    const toolElement = document.createElement('div');
                    toolElement.className = 'tool-call';
                    toolElement.dataset.toolIndex = index;
                    toolElement.dataset.toolName = tool.name; // 添加工具名称属性

                    // 获取工具显示名称和参数
                    const toolDisplayName = getToolDisplayName(tool.name);
                    const toolParams = formatToolParams(tool.params);

                    toolElement.innerHTML = `
                        <div class="tool-header">
                            <span class="tool-icon">🔧</span>
                            <span class="tool-name">${toolDisplayName}</span>
                            ${isPartial ? '<span class="tool-status">处理中...</span>' : ''}
                        </div>
                        <div class="tool-params">
                            ${toolParams}
                        </div>
                        ${!isPartial && tool.name !== 'attempt_completion' ? `
                            <div class="tool-actions" data-tool-index="${index}">
                                <button class="tool-approve" onclick="approveToolAction('${messageId}', ${index})">批准</button>
                                <button class="tool-reject" onclick="rejectToolAction('${messageId}', ${index})">拒绝</button>
                            </div>
                        ` : ''}
                        <div class="tool-result" data-tool-index="${index}" style="display:none;"></div>
                    `;

                    toolContainer.appendChild(toolElement);
                });
            } else if (parsedContent.textContent.length > 0) {
                // 有文本但没有工具调用
                toolContainer.style.display = 'none';
            }
        }

        // 提取工具调用
        function extractToolCall(text) {
            // 更高级的工具调用提取，支持多个工具调用和文本混合
            const toolCalls = [];
            const textContent = [];

            // 保存上一个匹配结束位置
            let lastIndex = 0;
            // 提取所有工具调用
            const toolRegex = /<([a-zA-Z_]+)>([\s\S]*?)<\/\1>/g;
            let match;

            while ((match = toolRegex.exec(text)) !== null) {
                // 添加工具调用前的文本
                if (match.index > lastIndex) {
                    textContent.push(text.substring(lastIndex, match.index));
                }

                const toolName = match[1];
                const toolContentRaw = match[2];

                // 提取参数
                const params = {};
                const paramRegex = /<([a-zA-Z_]+)>([\s\S]*?)<\/\1>/g;
                let paramMatch;

                while ((paramMatch = paramRegex.exec(toolContentRaw)) !== null) {
                    params[paramMatch[1]] = paramMatch[2].trim();
                }

                // 添加工具调用
                toolCalls.push({
                    name: toolName,
                    params,
                    startIndex: match.index,
                    endIndex: match.index + match[0].length
                });

                // 更新上一个匹配结束位置
                lastIndex = match.index + match[0].length;
            }

            // 添加最后一个工具调用后的文本
            if (lastIndex < text.length) {
                textContent.push(text.substring(lastIndex));
            }

            return {
                toolCalls,
                textContent,
                hasTools: toolCalls.length > 0
            };
        }

        // 格式化工具参数
        function formatToolParams(params) {
            let result = '<ul>';

            for (const key in params) {
                let value = params[key];
                if (key === 'content' && value.length > 100) {
                    // 对于文件内容，显示预览
                    value = `<pre class="code-preview">${escapeHtml(value.substring(0, 100))}...</pre>
                            <button class="show-more" onclick="showFullContent(this)">显示完整内容</button>
                            <pre class="full-content" style="display:none;">${escapeHtml(value)}</pre>`;
                } else {
                    value = escapeHtml(value);
                }

                result += `<li><strong>${key}:</strong> ${value}</li>`;
            }

            result += '</ul>';
            return result;
        }

        // 转义HTML
        function escapeHtml(text) {
            return text
                .replace(/&/g, "&amp;")
                .replace(/</g, "&lt;")
                .replace(/>/g, "&gt;")
                .replace(/"/g, "&quot;")
                .replace(/'/g, "&#039;");
        }



        // 处理工具结果
        function handleToolResult(message) {
            const toolId = message.toolId;
            const toolIndex = message.toolIndex || 0;
            const toolContainer = document.querySelector(`.tool-call-container[data-tool-id="${toolId}"]`);
            if (!toolContainer) return;

            // 获取指定索引的工具调用元素
            const toolElement = toolContainer.querySelector(`.tool-call[data-tool-index="${toolIndex}"]`);
            if (!toolElement) return;

            // 移除动作按钮
            const actionsDiv = toolElement.querySelector(`.tool-actions[data-tool-index="${toolIndex}"]`);
            if (actionsDiv) {
                actionsDiv.remove();
            }

            // 显示工具执行结果
            const resultDiv = toolElement.querySelector(`.tool-result[data-tool-index="${toolIndex}"]`);
            if (resultDiv) {
                resultDiv.style.display = 'block';

                if (message.success) {
                    resultDiv.innerHTML = `
                        <div class="tool-success">
                            <span class="result-icon">✅</span>
                            <span class="result-text">执行成功</span>
                        </div>
                        <div class="result-content">${formatToolResult(message.result)}</div>
                    `;
                } else {
                    resultDiv.innerHTML = `
                        <div class="tool-error">
                            <span class="result-icon">❌</span>
                            <span class="result-text">执行失败</span>
                        </div>
                        <div class="result-content">${message.error || '未知错误'}</div>
                    `;
                }
            }

            // 更新工具状态
            const statusSpan = toolElement.querySelector('.tool-status');
            if (statusSpan) {
                statusSpan.textContent = message.success ? '已完成' : '已拒绝';
            }
        }

        // 格式化工具结果
        function formatToolResult(result) {
            if (!result) return '无结果';

            if (typeof result === 'string') {
                return escapeHtml(result);
            }

            if (result.success === false) {
                return `<div class="error-message">${escapeHtml(result.error || '操作失败')}</div>`;
            }

            if (result.message) {
                return escapeHtml(result.message);
            }

            if (result.content) {
                return `<pre class="code-preview">${escapeHtml(result.content)}</pre>`;
            }

            return JSON.stringify(result, null, 2);
        }

        // 添加或更新推理块
        function addOrUpdateReasoning(text, isFirst = false) {
            if (currentReasoningBlock === null && isFirst) {
                // 首次接收推理内容，创建新的推理块
                currentReasoningBlock = createReasoningBlock(text);
                currentSessionHasReasoning = true;
                messagesDiv.appendChild(currentReasoningBlock);
            } else if (currentReasoningBlock !== null) {
                // 已有推理块，追加内容
                const reasoningContent = currentReasoningBlock.querySelector('.reasoning-content');
                if (reasoningContent) {
                    reasoningContent.textContent += text;
                }
            }

            // 滚动到底部（自动滚动实现）
            scrollToBottomIfNeeded();
        }

        // 滚动到底部（自动滚动实现）
        function scrollToBottomIfNeeded() {
            if (shouldAutoScroll) {
                messagesDiv.scrollTop = messagesDiv.scrollHeight;
            }
        }


        // 视图切换功能
        function switchToMcpManager() {
            document.getElementById('chat-container').style.display = 'none';
            document.getElementById('mcp-manager-container').style.display = 'block';

            // 初始化MCP管理界面数据
            vscode.postMessage({
                command: 'getMcpServers'
            });
        }

        function switchToChatView() {
            document.getElementById('chat-container').style.display = 'flex';
            document.getElementById('mcp-manager-container').style.display = 'none';
        }

        // 监听滚动事件，判断用户是否在底部
        messagesDiv.addEventListener('scroll', () => {
            const atBottom = messagesDiv.scrollHeight - messagesDiv.scrollTop - messagesDiv.clientHeight < 2;
            shouldAutoScroll = atBottom;
        });

        // MCP相关功能
        // MCP工具popup显示状态
        let mcpPopupVisible = false;
        // 添加跟踪当前选中服务器的变量
        let currentlySelectedServerName = null;

        // 初始化页面时设置调试日志
        console.log('初始化页面，设置MCP工具变量');

        // 初始化MCP按钮点击事件
        const mcpSymbolBtn = document.getElementById('mcp-symbol-btn');
        const mcpToolsPopup = document.getElementById('mcp-tools-popup');
        const mcpCloseBtn = document.getElementById('mcp-close-btn');
        const mcpSettingsBtn = document.getElementById('mcp-settings-btn');

        if (mcpSymbolBtn) {
            mcpSymbolBtn.addEventListener('click', toggleMcpToolsPopup);
        }

        if (mcpCloseBtn) {
            mcpCloseBtn.addEventListener('click', closeMcpToolsPopup);
        }

        if (mcpSettingsBtn) {
            mcpSettingsBtn.addEventListener('click', openMcpSettings);
        }

        // 控制MCP工具弹窗显示/隐藏
        function toggleMcpToolsPopup() {
            if (mcpPopupVisible) {
                closeMcpToolsPopup();
            } else {
                openMcpToolsPopup();
            }
        }

        // 打开MCP工具弹窗
        function openMcpToolsPopup() {
            mcpPopupVisible = true;
            mcpToolsPopup.style.display = 'flex';
            mcpSymbolBtn.classList.add('active');

            // 清空工具列表，初始为空
            const toolsList = document.getElementById('mcp-tools-list');
            if (toolsList) {
                toolsList.innerHTML = '';
            }
            
            // 重置当前选中的服务器
            currentlySelectedServerName = null;

            // 获取MCP服务器和工具信息
            console.log('打开工具弹窗，请求服务器列表');
            vscode.postMessage({
                command: 'getMcpServers'
            });
        }

        // 关闭MCP工具弹窗
        function closeMcpToolsPopup() {
            mcpPopupVisible = false;
            mcpToolsPopup.style.display = 'none';
            mcpSymbolBtn.classList.remove('active');
        }

        // 打开MCP设置
        function openMcpSettings() {
            vscode.postMessage({
                command: 'openMcpSettings',
                action: 'openFile' // 新增action参数，表示打开文件
            });
            closeMcpToolsPopup();
        }

        // 更新MCP服务器列表
        function updateMcpServers(servers) {
            const serversList = document.getElementById('mcp-servers-list');
            if (!serversList) return;

            // 清空当前列表
            serversList.innerHTML = '';

            if (!servers || servers.length === 0) {
                serversList.innerHTML = '<div class="mcp-empty-message">没有可用的MCP服务器</div>';
                return;
            }

                // 创建服务器项
            servers.forEach(server => {
                const serverItem = document.createElement('div');
                serverItem.className = 'mcp-server-item';
                serverItem.dataset.serverName = server.name;
                // 添加折叠状态类
                serverItem.classList.add('collapsed');

                // 服务器连接状态
                const statusClass = server.status === 'connected' ? 'connected' :
                    (server.status === 'connecting' ? 'connecting' : 'disconnected');

                // 设置服务器项内容 - 添加滑块控制禁用/启用
                serverItem.innerHTML = `
                    <div class="mcp-server-status ${statusClass}" title="${server.status}"></div>
                    <div class="mcp-server-name">${server.name}</div>
                    <div class="mcp-server-actions">
                        <label class="mcp-server-toggle" title="${server.disabled ? '启用服务器' : '禁用服务器'}">
                            <input type="checkbox" class="mcp-server-toggle-input" ${!server.disabled ? 'checked' : ''}>
                            <span class="mcp-server-slider"></span>
                        </label>
                    </div>
                `;

                // 创建和添加工具组容器 - 初始为隐藏状态
                const toolsGroup = document.createElement('div');
                toolsGroup.className = 'mcp-tools-group collapsed';
                toolsGroup.dataset.server = server.name;
                
                // 服务器点击处理逻辑 - 展开/折叠其下工具列表
                serverItem.addEventListener('click', (e) => {
                    // 忽略滑块区域的点击
                    if (e.target.closest('.mcp-server-actions')) {
                        return;
                    }
                    
                    e.stopPropagation();
                    
                    // 检查当前是否已经是展开状态
                    const isAlreadyExpanded = !serverItem.classList.contains('collapsed');
                    
                    // 如果已经是展开状态，则折叠并返回
                    if (isAlreadyExpanded) {
                        serverItem.classList.add('collapsed');
                        
                        // 隐藏对应的工具组
                        const currentToolsGroup = document.querySelector(`.mcp-tools-group[data-server="${server.name}"]`);
                        if (currentToolsGroup) {
                            currentToolsGroup.classList.add('collapsed');
                        }
                        return;
                    }
                    
                    // 折叠所有服务器项
                    document.querySelectorAll('.mcp-server-item').forEach(item => {
                        item.classList.add('collapsed');
                    });
                    
                    // 折叠所有工具组
                    document.querySelectorAll('.mcp-tools-group').forEach(group => {
                        group.classList.add('collapsed');
                    });
                    
                    // 展开当前服务器
                    serverItem.classList.remove('collapsed');
                    
                    // 更新当前选中的服务器
                    currentlySelectedServerName = server.name;
                    
                    // 查找该服务器对应的工具组
                    let toolsGroup = document.querySelector(`.mcp-tools-group[data-server="${server.name}"]`);
                    const toolsList = document.getElementById('mcp-tools-list');
                    
                    if (toolsGroup) {
                        // 如果工具组已存在，只需显示它
                        toolsGroup.classList.remove('collapsed');
                    } else if (toolsList) {
                        // 如果工具组不存在，创建一个临时的工具组显示加载状态
                        toolsGroup = document.createElement('div');
                        toolsGroup.className = 'mcp-tools-group';
                        toolsGroup.dataset.server = server.name;
                        toolsGroup.innerHTML = '<div class="mcp-empty-message">正在加载工具列表...</div>';
                        
                        // 添加到工具列表
                        toolsList.appendChild(toolsGroup);
                        
                        // 请求工具数据
                        console.log(`MCP弹窗：首次加载服务器 ${server.name} 的工具列表`);
                        vscode.postMessage({
                            command: 'getServerTools',
                            serverName: server.name
                        });
                    }
                });

                // 添加滑块切换事件 - 启用/禁用服务器
                const toggleInput = serverItem.querySelector('.mcp-server-toggle-input');
                if (toggleInput) {
                    toggleInput.addEventListener('change', (e) => {
                        e.stopPropagation(); // 防止触发服务器点击事件
                        console.log(`MCP弹窗：${e.target.checked ? '启用' : '禁用'}服务器 ${server.name}`);
                        
                        // 发送命令到后端
                        vscode.postMessage({
                            command: 'toggleServer',
                            serverName: server.name,
                            enable: e.target.checked
                        });
                    });
                }

                // 添加到服务器列表
                serversList.appendChild(serverItem);
            });

            // 默认保持所有服务器折叠状态
            if (servers.length > 0) {
                // 重置当前选择的服务器
                currentlySelectedServerName = null;
                
                // 确保所有服务器项处于折叠状态
                document.querySelectorAll('.mcp-server-item').forEach(item => {
                    item.classList.add('collapsed');
                });
                
                // 确保所有工具组处于折叠状态
                document.querySelectorAll('.mcp-tools-group').forEach(group => {
                    group.classList.add('collapsed');
                });
            }
        }

        // 更新MCP工具列表
        function updateMcpTools(server) {
            const toolsList = document.getElementById('mcp-tools-list');
            if (!toolsList) {
                console.error('MCP弹窗：找不到工具列表容器');
                return;
            }

            // 确保server对象存在
            if (!server) {
                console.error('MCP弹窗：服务器数据无效');
                return;
            }

            // 提取服务器名称和工具
            const serverName = server.serverName || server.name;
            const tools = server.tools || [];
            
            console.log(`MCP弹窗：更新服务器 ${serverName} 的工具，共 ${tools.length} 个工具`);

            // 查找该服务器的工具组，如果存在则更新，不存在则创建
            let toolsGroup = document.querySelector(`.mcp-tools-group[data-server="${serverName}"]`);
            
            if (!toolsGroup) {
                // 如果不存在，创建新的工具组
                toolsGroup = document.createElement('div');
                toolsGroup.className = 'mcp-tools-group';
                toolsGroup.dataset.server = serverName;
                toolsList.appendChild(toolsGroup);
            } else {
                // 如果存在，清空其内容以更新
                toolsGroup.innerHTML = '';
            }

            // 如果没有工具，显示空消息
            if (!tools || tools.length === 0) {
                console.log(`MCP弹窗：服务器 ${serverName} 没有工具`);
                toolsGroup.innerHTML = `<div class="mcp-empty-message">服务器 ${serverName} 没有可用工具</div>`;
                return;
            }

            // 创建标题
            const groupTitle = document.createElement('div');
            groupTitle.className = 'mcp-tools-group-title';
            groupTitle.textContent = `${serverName} 可用工具 (${tools.length})`;
            toolsGroup.appendChild(groupTitle);

            // 添加工具项
            tools.forEach(tool => {
                console.log(`MCP弹窗：添加工具 ${tool.name}`);
                const toolItem = document.createElement('div');
                toolItem.className = 'mcp-tool-item';

                toolItem.innerHTML = `
                    <div class="mcp-tool-icon">⚡</div>
                    <div class="mcp-tool-details">
                        <div class="mcp-tool-name">${tool.name}</div>
                        ${tool.description ? `<div class="mcp-tool-description">${tool.description}</div>` : ''}
                    </div>
                `;

                // 点击工具，将工具调用模板添加到输入框
                toolItem.addEventListener('click', () => {
                    const template = `<mcp-tool server="${serverName}" tool="${tool.name}" params={"param1": "value1"}></mcp-tool>`;
                    addToInput(template);
                    closeMcpToolsPopup();
                });

                toolsGroup.appendChild(toolItem);
            });

            console.log(`MCP弹窗：完成添加 ${tools.length} 个工具`);

            // 检查对应的服务器项是否展开
            const serverItem = document.querySelector(`.mcp-server-item[data-server-name="${serverName}"]`);
            if (serverItem && !serverItem.classList.contains('collapsed')) {
                // 如果服务器项已展开，显示工具组
                toolsGroup.classList.remove('collapsed');
            } else {
                // 否则保持工具组为折叠状态
                toolsGroup.classList.add('collapsed');
            }
        }

        // 添加内容到输入框
        function addToInput(text) {
            const input = document.getElementById('message-input');
            if (input) {
                // 如果输入框已有内容，添加空格
                if (input.value && !input.value.endsWith(' ')) {
                    input.value += ' ';
                }

                input.value += text;
                input.focus();

                // 调整输入框高度
                input.style.height = 'auto';
                input.style.height = Math.min(input.scrollHeight, 200) + 'px';
            }
        }

        // 展示高风险操作用户确认框
        function showUserApproval(toolName, params, path) {
            // 先移除已有的确认框
            let old = document.getElementById('user-approval-box');
            if (old) old.remove();

            // 构建描述
            let desc = '';
            if (toolName === 'execute_command') {
                desc = `即将执行命令：${params.command}`;
            } else if (toolName === 'delete_file') {
                desc = `即将删除文件：${path}`;
            } else {
                desc = '即将执行高风险操作';
            }

            // 创建遮罩层
            const overlay = document.createElement('div');
            overlay.className = 'overlay';
            document.body.appendChild(overlay);

            // 创建确认框
            const box = document.createElement('div');
            box.id = 'user-approval-box';
            box.className = 'user-approval-box';
            box.innerHTML = `
                <div class="title">需要确认</div>
                <div class="description">${desc}</div>
                <div class="buttons">
                    <button class="approve-btn">允许</button>
                    <button class="reject-btn">拒绝</button>
                </div>
            `;
            document.body.appendChild(box);

            // 点击事件处理
            box.querySelector('.approve-btn').onclick = function () {
                vscode.postMessage({ command: 'userApproval', approved: true });
                box.remove();
                overlay.remove();
            };
            box.querySelector('.reject-btn').onclick = function () {
                vscode.postMessage({ command: 'userApproval', approved: false });
                box.remove();
                overlay.remove();
            };
        }

        // 添加@提及相关变量
        let showContextMenu = false;
        let contextMenuItems = [];
        let selectedContextMenuIndex = 0;
        let contextMenuQuery = '';
        let contextMenuContainer = null;
        let isSearchingFiles = false;
        let searchTimeout = null;
        let mentionTags = [];

        // 添加@按钮点击事件
        document.getElementById('at-symbol-btn').addEventListener('click', () => {
            // 获取输入框
            const inputElement = document.getElementById('message-input');
            // 在光标位置插入@符号
            const cursorPosition = inputElement.selectionStart;
            const text = inputElement.value;
            const newText = text.slice(0, cursorPosition) + '@' + text.slice(cursorPosition);

            // 更新输入框内容
            inputElement.value = newText;
            inputElement.selectionStart = inputElement.selectionEnd = cursorPosition + 1;

            // 聚焦输入框
            inputElement.focus();

            // 显示上下文菜单
            showContextMenu = true;
            selectedContextMenuIndex = 0;
            contextMenuQuery = '';

            // 初始菜单项
            contextMenuItems = [
                { type: 'problems', label: '工作区问题' },
                { type: 'terminal', label: '终端输出' },
                { type: 'git', value: 'git-changes', label: '工作区变更' }
            ];

            renderContextMenu();
        });

        // 输入框的键盘事件处理，添加@菜单相关逻辑
        messageInput.addEventListener('keydown', (e) => {
            // 处理@符号菜单相关的键盘事件
            if (showContextMenu) {
                if (e.key === 'ArrowDown') {
                    e.preventDefault();
                    selectedContextMenuIndex = Math.min(selectedContextMenuIndex + 1, contextMenuItems.length - 1);
                    renderContextMenu();
                } else if (e.key === 'ArrowUp') {
                    e.preventDefault();
                    selectedContextMenuIndex = Math.max(selectedContextMenuIndex - 1, 0);
                    renderContextMenu();
                } else if (e.key === 'Enter' || e.key === 'Tab') {
                    e.preventDefault();
                    selectContextMenuItem();
                } else if (e.key === 'Escape') {
                    e.preventDefault();
                    hideContextMenu();
                }
            } else {
                // 原有的Enter键逻辑
                if (e.key === 'Enter') {
                    if (e.shiftKey) {
                        // Shift+Enter: 插入换行符
                        const start = messageInput.selectionStart;
                        const end = messageInput.selectionEnd;
                        const value = messageInput.value;
                        messageInput.value = value.substring(0, start) + '\n' + value.substring(end);
                        messageInput.selectionStart = messageInput.selectionEnd = start + 1;

                        // 调整输入框高度
                        messageInput.style.height = 'auto';
                        messageInput.style.height = Math.min(messageInput.scrollHeight, 200) + 'px';

                        e.preventDefault();
                    } else {
                        // 普通Enter: 发送消息
                        e.preventDefault();
                        sendMessage();
                    }
                }
            }
        });

        // 输入框内容变化事件，检测@符号并显示菜单
        messageInput.addEventListener('input', () => {
            // 调整输入框高度
            messageInput.style.height = 'auto';
            messageInput.style.height = Math.min(messageInput.scrollHeight, 200) + 'px';

            // 检查是否应该显示@菜单
            const cursorPosition = messageInput.selectionStart;
            const text = messageInput.value;

            // 检查光标前的文本是否包含@符号
            if (shouldShowContextMenu(text, cursorPosition)) {
                // 提取查询文本
                const beforeCursor = text.slice(0, cursorPosition);
                const atIndex = beforeCursor.lastIndexOf('@');
                contextMenuQuery = beforeCursor.slice(atIndex + 1);

                // 显示上下文菜单
                showContextMenu = true;
                selectedContextMenuIndex = 0;

                // 初始菜单项
                contextMenuItems = [
                    { type: 'problems', label: '工作区问题' },
                    { type: 'terminal', label: '终端输出' },
                    { type: 'git', value: 'git-changes', label: '工作区变更' }
                ];

                // 如果查询不为空，使用延迟搜索文件
                if (contextMenuQuery.trim()) {
                    // 设置搜索状态
                    isSearchingFiles = true;

                    // 取消之前的搜索
                    if (searchTimeout) {
                        clearTimeout(searchTimeout);
                    }

                    // 延迟搜索以减少请求
                    searchTimeout = setTimeout(() => {
                        // 发送搜索请求到扩展
                        vscode.postMessage({
                            command: 'searchFiles',
                            query: contextMenuQuery
                        });
                    }, 300);
                }

                renderContextMenu();
            } else {
                // 只有当@符号不存在时才隐藏菜单
                hideContextMenu();
            }
        });

        // 在输入框失焦时不要立即隐藏上下文菜单，让用户有时间点击
        messageInput.addEventListener('blur', () => {
            // 延迟更长时间来隐藏，以便点击菜单有效
            setTimeout(() => {
                // 检查光标位置是否仍在输入框内
                const text = messageInput.value;
                const cursorPosition = messageInput.selectionStart;

                // 仅当@符号不在文本中时才隐藏菜单
                if (!shouldShowContextMenu(text, cursorPosition)) {
                    hideContextMenu();
                }
            }, 500);
        });

        // 渲染上下文菜单
        function renderContextMenu() {
            if (!showContextMenu) return;

            // 如果容器不存在，创建一个
            if (!contextMenuContainer) {
                contextMenuContainer = document.createElement('div');
                contextMenuContainer.className = 'context-menu-container';
                document.getElementById('input-container').appendChild(contextMenuContainer);
            }

            // 构建菜单HTML
            let menuHTML = '<div class="context-menu">';

            // 添加加载指示器（如果在搜索）
            if (isSearchingFiles && contextMenuQuery.trim()) {
                menuHTML += `
                    <div class="context-menu-loading">
                        <span class="codicon codicon-loading codicon-modifier-spin"></span>
                        <span>搜索中...</span>
                    </div>
                `;
            }

            // 添加菜单选项
            contextMenuItems.forEach((item, index) => {
                const isSelected = index === selectedContextMenuIndex;
                const isSelectable = item.type !== 'noResults';

                menuHTML += `
                    <div class="context-menu-option ${isSelected ? 'selected' : ''} ${!isSelectable ? 'no-select' : ''}" 
                         data-index="${index}" data-type="${item.type}" ${item.value ? `data-value="${item.value}"` : ''}>
                        <div class="context-menu-option-content">
                            <span class="context-menu-icon codicon codicon-${getIconForContextMenu(item.type)}"></span>
                            ${renderContextMenuContent(item)}
                        </div>
                        ${(item.type === 'file' || item.type === 'folder' || item.type === 'git') && !item.value ?
                        '<span class="context-menu-arrow codicon codicon-chevron-right"></span>' : ''}
                    </div>
                `;
            });

            menuHTML += '</div>';

            // 更新菜单内容
            contextMenuContainer.innerHTML = menuHTML;

            // 添加点击事件处理
            const options = contextMenuContainer.querySelectorAll('.context-menu-option');
            options.forEach(option => {
                if (!option.classList.contains('no-select')) {
                    option.addEventListener('click', () => {
                        const index = parseInt(option.dataset.index);
                        selectedContextMenuIndex = index;
                        selectContextMenuItem();
                    });
                }
            });
        }

        // 隐藏上下文菜单
        function hideContextMenu() {
            showContextMenu = false;
            isSearchingFiles = false;
            if (contextMenuContainer) {
                contextMenuContainer.innerHTML = '';
            }
        }

        // 选择当前菜单项
        function selectContextMenuItem() {
            if (!showContextMenu || contextMenuItems.length === 0) return;

            const selectedItem = contextMenuItems[selectedContextMenuIndex];
            if (!selectedItem || selectedItem.type === 'noResults') return;

            // 插入选中的项
            const cursorPosition = messageInput.selectionStart;
            const text = messageInput.value;

            // 根据类型生成要插入的值
            let valueToInsert = '';
            let displayValue = '';
            let itemType = selectedItem.type;

            switch (selectedItem.type) {
                case 'problems':
                    valueToInsert = 'problems';
                    displayValue = '工作区问题';
                    break;
                case 'terminal':
                    valueToInsert = 'terminal';
                    displayValue = '终端输出';
                    break;
                case 'file':
                    valueToInsert = selectedItem.value || '';
                    displayValue = selectedItem.label || selectedItem.value || '';
                    break;
                case 'folder':
                    valueToInsert = selectedItem.value || '';
                    displayValue = selectedItem.label || selectedItem.value || '';
                    break;
                case 'git':
                    valueToInsert = selectedItem.value || '';
                    displayValue = selectedItem.label || '工作区变更';
                    break;
                default:
                    valueToInsert = selectedItem.value || selectedItem.label || '';
                    displayValue = selectedItem.label || selectedItem.value || '';
            }

            // 查找并替换@提及的文本
            const beforeCursor = text.slice(0, cursorPosition);
            const afterCursor = text.slice(cursorPosition);
            const atIndex = beforeCursor.lastIndexOf('@');

            if (atIndex !== -1) {
                // 删除@开头的文本
                const newText = text.slice(0, atIndex) + text.slice(cursorPosition);
                messageInput.value = newText;

                // 添加标签
                createMentionTag(valueToInsert, displayValue, atIndex, itemType);

                // 更新光标位置
                messageInput.selectionStart = messageInput.selectionEnd = atIndex;
            }

            // 隐藏菜单
            hideContextMenu();

            // 聚焦输入框
            messageInput.focus();
        }

        // 创建提及标签
        function createMentionTag(value, displayText, position, type = 'text') {
            const inputElement = document.getElementById('message-input');
            const wrapper = document.createElement('span');
            wrapper.className = 'mention-tag';
            wrapper.innerHTML = `
                <span class="mention-tag-text">@${displayText}</span>
                <span class="mention-tag-remove">×</span>
            `;

            // 添加标签到标签容器
            const tagsContainer = document.getElementById('tags-container');

            // 存储标签信息
            const tagId = 'tag-' + Date.now();
            wrapper.id = tagId;
            wrapper.dataset.value = value;
            wrapper.dataset.position = position;
            wrapper.dataset.type = type;

            mentionTags.push({
                id: tagId,
                element: wrapper,
                value,
                displayText,
                position,
                type
            });

            // 添加删除事件
            wrapper.querySelector('.mention-tag-remove').addEventListener('click', () => {
                removeMentionTag(tagId);
            });

            // 添加到DOM（添加到@按钮之后）
            tagsContainer.appendChild(wrapper);
        }

        // 获取文本位置 - 不再需要，标签直接放在容器中
        function getTextPosition(element, position) {
            return { left: 0, top: 0 }; // 简化，不需要计算位置
        }

        // 移除提及标签
        function removeMentionTag(tagId) {
            // 查找标签
            const tagIndex = mentionTags.findIndex(tag => tag.id === tagId);
            if (tagIndex === -1) return;

            const tag = mentionTags[tagIndex];

            // 移除DOM元素
            if (tag.element && tag.element.parentElement) {
                tag.element.parentElement.removeChild(tag.element);
            }

            // 从数组中移除
            mentionTags.splice(tagIndex, 1);
        }

        // 发送消息时处理标签
        const originalSendMessage = sendMessage;
        sendMessage = function () {
            const inputElement = document.getElementById('message-input');
            let text = inputElement.value.trim();

            // 如果有标签，将标签添加到文本中
            mentionTags.forEach(tag => {
                // 根据不同的类型，格式化@提及内容
                let mentionValue = tag.value;

                // 确保文件和文件夹路径以/开头
                if (tag.type === 'file' || tag.type === 'folder') {
                    mentionValue = mentionValue.startsWith('/') ? mentionValue : `/${mentionValue}`;
                }

                // 确保文件夹路径以/结尾
                if (tag.type === 'folder' && !mentionValue.endsWith('/')) {
                    mentionValue = `${mentionValue}/`;
                }

                // 添加到文本
                text = `${text} @${mentionValue}`;
            });

            // 清空标签数组
            mentionTags.forEach(tag => {
                if (tag.element && tag.element.parentElement) {
                    tag.element.parentElement.removeChild(tag.element);
                }
            });
            mentionTags = [];

            // 设置新的文本
            inputElement.value = text;

            // 调用原始发送函数
            originalSendMessage();
        };

        // 获取上下文菜单项的图标
        function getIconForContextMenu(type) {
            switch (type) {
                case 'file': return 'file';
                case 'folder': return 'folder';
                case 'problems': return 'warning';
                case 'terminal': return 'terminal';
                case 'url': return 'link';
                case 'git': return 'git-commit';
                case 'noResults': return 'info';
                default: return 'file';
            }
        }

        // 渲染上下文菜单项的内容
        function renderContextMenuContent(item) {
            switch (item.type) {
                case 'problems':
                    return '<span class="context-menu-label">工作区问题</span>';
                case 'terminal':
                    return '<span class="context-menu-label">终端输出</span>';
                case 'url':
                    return '<span class="context-menu-label">粘贴URL以获取内容</span>';
                case 'noResults':
                    return '<span class="context-menu-label">未找到结果</span>';
                case 'git':
                    if (item.value) {
                        return `
                            <div class="git-option-content">
                                <span class="context-menu-label">${item.label || ''}</span>
                                ${item.description ? `<span class="context-menu-description">${item.description}</span>` : ''}
                            </div>
                        `;
                    } else {
                        return '<span class="context-menu-label">Git提交</span>';
                    }
                case 'file':
                case 'folder':
                    if (item.value) {
                        return `
                            <div class="path-container">
                                <span class="path-prefix">/</span>
                                ${item.value.startsWith('/.') ? '<span class="path-dot">.</span>' : ''}
                                <span class="path-content">${(item.value || '').replace(/^\//, '') + '\u200E'}</span>
                            </div>
                        `;
                    } else {
                        return `<span class="context-menu-label">添加${item.type === 'file' ? '文件' : '文件夹'}</span>`;
                    }
                default:
                    return `<span class="context-menu-label">${item.label || item.value || ''}</span>`;
            }
        }

        // 判断是否应显示上下文菜单
        function shouldShowContextMenu(text, position) {
            if (!text) return false;

            const beforeCursor = text.slice(0, position);
            const atIndex = beforeCursor.lastIndexOf('@');

            // 只要@符号存在且未被删除即可显示菜单
            return atIndex !== -1;
        }

        // 处理扩展发来的搜索结果
        window.addEventListener('message', event => {
            const message = event.data;

            if (message.command === 'searchFilesResult') {
                // 更新搜索状态
                isSearchingFiles = false;

                // 如果菜单已关闭，不处理
                if (!showContextMenu) return;

                // 保存基本条目（problems、terminal等）
                const basicItems = contextMenuItems.filter(item =>
                    item.type === 'problems' ||
                    item.type === 'terminal' ||
                    item.type === 'git' && item.value === 'git-changes'
                );

                // 添加搜索结果
                contextMenuItems = [
                    ...basicItems,
                    ...message.results.map(result => ({
                        type: result.type,
                        value: result.path.startsWith('/') ? result.path : `/${result.path}`,
                        label: result.label || path.basename(result.path),
                        description: result.path
                    }))
                ];

                // 如果没有结果，添加"未找到结果"项
                if (contextMenuItems.length === 0) {
                    contextMenuItems.push({ type: 'noResults' });
                }

                // 重置选择索引
                selectedContextMenuIndex = 0;

                // 重新渲染菜单
                renderContextMenu();
            }
        });

        // 添加到原有的消息处理
        // 向用户展示选项
        function showOptionsDialog(message, options) {
            console.log("showOptionsDialog", message, options);

            // 确保options是数组
            if (!Array.isArray(options)) {
                console.error("选项必须是数组类型", options);
                if (typeof options === 'string') {
                    // 尝试将逗号分隔的字符串转换为数组
                    options = options.split(',').map(opt => opt.trim());
                } else {
                    // 如果无法处理，则创建一个默认选项数组
                    options = ["选项1", "选项2", "选项3"];
                }
            }

            // 创建选项容器
            const optionsContainer = document.createElement('div');
            optionsContainer.className = 'message bot-message options-message';

            // 创建消息内容容器
            const contentEl = document.createElement('div');
            contentEl.className = 'message-content';

            // 创建消息气泡
            const bubbleEl = document.createElement('div');
            bubbleEl.className = 'message-bubble options-bubble';
            bubbleEl.style.width = '95%'; // 设置宽度为95%

            // 创建标题
            const titleEl = document.createElement('div');
            titleEl.className = 'options-title';
            titleEl.textContent = message || '请选择一个选项';
            bubbleEl.appendChild(titleEl);

            // 创建选项列表
            const optionsListEl = document.createElement('div');
            optionsListEl.className = 'options-list';

            // 创建选项项
            options.forEach((option, index) => {
                const optionItem = document.createElement('div');
                optionItem.className = 'option-item';
                optionItem.dataset.value = option;
                optionItem.dataset.index = index;

                optionItem.innerHTML = `
                    <div class="option-radio"></div>
                    <div class="option-label">${option}</div>
                `;

                // 点击选项直接确认选择
                optionItem.addEventListener('click', () => {
                    // 禁用所有选项
                    Array.from(optionsListEl.querySelectorAll('.option-item')).forEach(item => {
                        item.style.pointerEvents = 'none';
                        item.style.opacity = '0.7';
                    });

                    // 选中当前选项
                    optionItem.classList.add('selected');

                    // 添加选择结果提示
                    const resultEl = document.createElement('div');
                    resultEl.className = 'option-result';
                    resultEl.textContent = `已选择: ${option}`;
                    bubbleEl.appendChild(resultEl);

                    console.log(`用户选择了选项: ${option} (索引: ${index})`);

                    // 发送用户选择结果给扩展
                    vscode.postMessage({
                        command: 'userApproval',
                        approved: true,
                        selectedOption: option
                    });
                });

                optionsListEl.appendChild(optionItem);
            });
            bubbleEl.appendChild(optionsListEl);

            contentEl.appendChild(bubbleEl);
            optionsContainer.appendChild(contentEl);

            // 将选项容器添加到消息列表
            messagesDiv.appendChild(optionsContainer);

            // 滚动到底部
            scrollToBottomIfNeeded();
        }

        // 处理文件变更相关功能
        let pendingChanges = {}; // 储存待确认的变更
        let confirmedChanges = {}; // 储存已确认的变更

        // 重置所有文件变更
        function resetFileChanges() {
            pendingChanges = {};
            confirmedChanges = {};
            updateChangesUI();
            console.log('已重置所有文件变更');
        }

        // 添加变更
        function addPendingChange(filePath, operation, changeInfo) {
            pendingChanges[filePath] = {
                filePath,
                operation,
                timestamp: Date.now(),
                changeInfo: changeInfo || {}
            };

            updateChangesUI();
        }

        // 移除变更
        function removePendingChange(filePath) {
            delete pendingChanges[filePath];
            updateChangesUI();
        }

        // 添加已确认变更
        function addConfirmedChange(filePath, operation) {
            confirmedChanges[filePath] = {
                filePath,
                operation,
                timestamp: Date.now(),
                confirmed: true
            };

            updateChangesUI();
        }

        // 计算变更行数
        function calculateChangeStats(originalContent, newContent) {
            if (!originalContent && !newContent) return { added: 0, removed: 0 };

            const originalLines = originalContent ? originalContent.split('\n') : [];
            const newLines = newContent ? newContent.split('\n') : [];

            // 简单计算增减行数
            return {
                added: Math.max(0, newLines.length - originalLines.length),
                removed: Math.max(0, originalLines.length - newLines.length)
            };
        }

        // 更新文件变更UI
        function updateChangesUI() {
            const container = document.getElementById('pending-changes');
            const changesList = document.getElementById('changes-list');

            // 检查是否有变更
            const pendingCount = Object.keys(pendingChanges).length;
            const confirmedCount = Object.keys(confirmedChanges).length;
            const hasChanges = pendingCount > 0 || confirmedCount > 0;
            container.style.display = hasChanges ? 'block' : 'none';

            if (!hasChanges) return;

            // 更新变更列表
            changesList.innerHTML = '';

            // 先显示待确认变更
            Object.values(pendingChanges).forEach(change => {
                const item = document.createElement('div');
                item.className = 'change-item';
                item.dataset.path = change.filePath;
                item.dataset.status = 'pending';

                // 统计变更行数
                let statsHtml = '';
                if (change.changeInfo) {
                    const added = change.changeInfo.added || 0;
                    const removed = change.changeInfo.removed || 0;
                    if (added > 0 || removed > 0) {
                        statsHtml = `
                            <div class="change-stats">
                                ${added > 0 ? `<span class="stats-added">+${added}</span>` : ''}
                                ${removed > 0 ? `<span class="stats-removed">-${removed}</span>` : ''}
                            </div>
                        `;
                    }
                }

                item.innerHTML = `
                    <div class="change-path">${change.filePath}</div>
                    ${statsHtml}
                    <div class="change-operation ${change.operation}">${getOperationName(change.operation)}</div>
                    <div class="change-actions">
                        <button class="change-accept" title="接受变更">✓</button>
                        <button class="change-reject" title="拒绝变更">✗</button>
                    </div>
                `;

                // 添加点击文件名打开差异预览
                item.querySelector('.change-path').addEventListener('click', () => {
                    openDiffView(change.filePath);
                });

                // 添加按钮事件
                item.querySelector('.change-accept').addEventListener('click', () => {
                    acceptChange(change.filePath);
                });

                item.querySelector('.change-reject').addEventListener('click', () => {
                    rejectChange(change.filePath);
                });

                changesList.appendChild(item);
            });

            // 然后显示已确认变更
            Object.values(confirmedChanges).forEach(change => {
                const item = document.createElement('div');
                item.className = 'change-item';
                item.dataset.path = change.filePath;
                item.dataset.status = 'confirmed';

                item.innerHTML = `
                    <div class="change-path">${change.filePath}</div>
                    <div class="change-status confirmed">已完成</div>
                    <div class="change-operation ${change.operation}">${getOperationName(change.operation)}</div>
                `;

                // 添加点击文件名直接打开文件
                item.querySelector('.change-path').addEventListener('click', () => {
                    openFile(change.filePath);
                });

                changesList.appendChild(item);
            });
        }

        // 打开差异预览
        function openDiffView(filePath) {
            vscode.postMessage({
                command: 'openDiffView',
                filePath: filePath
            });
        }

        // 打开文件
        function openFile(filePath) {
            vscode.postMessage({
                command: 'openFile',
                filePath: filePath
            });
        }

        // 接受单个变更
        function acceptChange(filePath) {
            vscode.postMessage({
                command: 'acceptChange',
                filePath: filePath
            });
        }

        // 拒绝单个变更
        function rejectChange(filePath) {
            vscode.postMessage({
                command: 'rejectChange',
                filePath: filePath
            });
        }

        // 获取操作名称
        function getOperationName(operation) {
            switch (operation) {
                case 'write': return '新建';
                case 'replace': return '修改';
                default: return operation;
            }
        }

        // 绑定全部接受/拒绝按钮事件
        document.getElementById('accept-all-changes')?.addEventListener('click', () => {
            vscode.postMessage({
                command: 'acceptAllChanges'
            });
        });

        document.getElementById('reject-all-changes')?.addEventListener('click', () => {
            vscode.postMessage({
                command: 'rejectAllChanges'
            });
        });

        // 监听文件变更消息
        window.addEventListener('message', event => {
            const message = event.data;

            if (message.command === 'fileChanged') {
                console.log('收到文件变更信息:', message); // 添加调试信息
                // 添加变更行数统计
                addPendingChange(message.filePath, message.operation, message.changeInfo);
            } else if (message.command === 'fileChangeConfirmed') {
                removePendingChange(message.filePath);
                addConfirmedChange(message.filePath, message.operation);
            } else if (message.command === 'fileChangeRejected') {
                // 通知变更拒绝
                removePendingChange(message.filePath);
            } else if (message.command === 'resetFileChanges') {
                // 重置所有文件变更
                resetFileChanges();
            } else if (message.command === 'mcpServersUpdated') {
                // 更新MCP服务器列表
                if (message.servers) {
                    updateMcpServers(message.servers);
                }
            } else if (message.command === 'mcpServerToolsUpdated') {
                // 更新特定服务器的工具列表
                if (message.server) {
                    updateMcpTools(message.server);
                }
            } else {
                console.log('Unhandled message:', message);
            }
        });

        // 展示MCP工具调用确认对话框
        function showMcpToolApproval(toolName, serverName, params) {
            // 先移除已有的确认框
            let old = document.getElementById('mcp-tool-approval-box');
            if (old) old.remove();

            // 构建描述
            let desc = `服务器 "${serverName}" 请求执行工具 "${toolName}"`;
            let paramsDesc = '';

            try {
                if (params && typeof params === 'object') {
                    paramsDesc = JSON.stringify(params, null, 2);
                } else if (typeof params === 'string') {
                    paramsDesc = params;
                }
            } catch (e) {
                paramsDesc = '无法显示参数';
            }

            // 创建遮罩层
            const overlay = document.createElement('div');
            overlay.className = 'overlay';
            document.body.appendChild(overlay);

            // 创建确认框
            const box = document.createElement('div');
            box.id = 'mcp-tool-approval-box';
            box.className = 'user-approval-box';
            box.innerHTML = `
                <div class="title">MCP工具调用确认</div>
                <div class="description">${desc}</div>

                <div class="buttons">
                    <button class="approve-btn">允许</button>
                    <button class="reject-btn">拒绝</button>
                </div>
            `;
            document.body.appendChild(box);

            // 点击事件处理
            box.querySelector('.approve-btn').onclick = function () {
                vscode.postMessage({ command: 'mcpApproval', approved: true });
                box.remove();
                overlay.remove();
            };
            box.querySelector('.reject-btn').onclick = function () {
                vscode.postMessage({ command: 'mcpApproval', approved: false });
                box.remove();
                overlay.remove();
            };
        }

        // 接收来自扩展的消息
        window.addEventListener('message', event => {
            const message = event.data;

            switch (message.command) {
                // ... existing code ...
                case 'userApproval':
                    // 处理高风险操作用户确认
                    if (message.toolName && message.params) {
                        showUserApproval(message.toolName, message.params, message.path);
                    }
                    break;

                case 'mcpToolApproval':
                    // 处理MCP工具调用确认
                    if (message.toolName && message.serverName) {
                        showMcpToolApproval(message.toolName, message.serverName, message.params);
                    }
                    break;
                // ... existing code ...
            }
        });

        // 处理MCP工具执行结果
        function handleMcpToolResult(message) {
            console.log('收到MCP工具执行结果:', message);
            // 获取消息区域元素
            const messagesDiv = document.getElementById('messages');
            if (!messagesDiv) return;

            // 提取错误信息（如果有）
            let errorMessage = "";
            // 初始状态基于message.success，如果success为false则认为是错误
            let isError = !message.success;
            let resultContent = null;

            // 处理result中的内容
            if (message.result) {
                // 如果result中isError为true，则无论message.success如何，都视为错误
                if (message.result.isError === true) {
                    isError = true;
                }

                // 从content数组中提取文本内容
                if (message.result.content && Array.isArray(message.result.content)) {
                    const textItems = message.result.content.filter(item =>
                        item.type === 'text' && item.text
                    );

                    if (textItems.length > 0) {
                        // 只显示text内容
                        resultContent = textItems.map(item => item.text).join('\n');
                    }
                }
            }

            // 构建MCP工具结果块
            const resultBlock = document.createElement('div');
            resultBlock.className = `message bot-message mcp-result-message ${isError ? 'error' : 'success'}`;

            // 设置结果块内容
            resultBlock.innerHTML = `
                <div class="message-content">
                    <div class="message-bubble mcp-result-bubble ${isError ? 'error' : 'success'}">
                        <div class="mcp-result-header">
                            <span class="mcp-result-icon">${isError ? '❌' : '✅'}</span>
                            <span class="mcp-result-title">${message.serverName}.${message.toolName} ${isError ? '执行失败' : '执行成功'}</span>
                        </div>
                        <div class="mcp-result-content">
                            ${isError
                    ? `<div class="mcp-error-message">${escapeHtml(resultContent || "未知错误")}</div>`
                    : renderSuccessResult(resultContent || message.result)
                }
                        </div>
                    </div>
                </div>
            `;

            // 添加到消息区域
            messagesDiv.appendChild(resultBlock);

            // 滚动到底部
            scrollToBottomIfNeeded();

            // 将结果添加到状态中
            const resultMessage = {
                sender: 'bot',
                type: 'mcp_result',
                text: `MCP工具 ${message.serverName}.${message.toolName} ${isError ? '执行失败' : '执行成功'}`,
                serverName: message.serverName,
                toolName: message.toolName,
                success: !isError,
                result: !isError ? resultContent || message.result : null,
                error: isError ? resultContent : null,
                timestamp: new Date().toISOString()
            };

            messagesState.push(resultMessage);
            vscode.setState({ messages: messagesState });
            saveStateToExtension();
        }

        // 渲染成功结果内容
        function renderSuccessResult(result) {
            if (!result) {
                return `<div class="mcp-result-success">工具执行成功，无返回值</div>`;
            }

            try {
                // 尝试序列化和格式化结果
                let resultContent = '';

                if (typeof result === 'object') {
                    // 如果是对象，尝试格式化为JSON
                    try {
                        resultContent = `<pre class="mcp-result-json">${escapeHtml(JSON.stringify(result, null, 2))}</pre>`;
                    } catch (e) {
                        resultContent = `<div class="mcp-result-value">${escapeHtml(String(result))}</div>`;
                    }
                } else if (typeof result === 'string') {
                    // 检查字符串是否是JSON
                    try {
                        const jsonObj = JSON.parse(result);
                        resultContent = `<pre class="mcp-result-json">${escapeHtml(JSON.stringify(jsonObj, null, 2))}</pre>`;
                    } catch (e) {
                        // 不是有效的JSON，普通显示
                        resultContent = `<div class="mcp-result-text">${escapeHtml(result)}</div>`;
                    }
                } else {
                    // 其他类型直接转字符串
                    resultContent = `<div class="mcp-result-value">${escapeHtml(String(result))}</div>`;
                }

                return resultContent;
            } catch (e) {
                return `<div class="mcp-result-error">无法显示结果: ${escapeHtml(e.message)}</div>`;
            }
        }

        // MCP管理界面相关函数
        // 添加返回聊天按钮的事件处理
        document.getElementById('back-to-chat').addEventListener('click', () => {
            switchToChatView();
        });

        // 添加刷新按钮的事件处理
        document.getElementById('refresh')?.addEventListener('click', () => {
            vscode.postMessage({
                command: 'showInformation',
                message: '正在刷新服务器列表...'
            });
            vscode.postMessage({
                command: 'getMcpServers' // 确保发送正确的命令
            });
        });

        // 添加服务器按钮的事件处理
        document.getElementById('add-server')?.addEventListener('click', () => {
            vscode.postMessage({
                command: 'addServer'
            });
        });

        // 更新服务器列表
        function updateServersList(servers) {
            const serversList = document.getElementById('servers-list');
            if (!serversList) return;

            // 清空当前列表
            serversList.innerHTML = '';

            if (!servers || servers.length === 0) {
                serversList.innerHTML = '<div class="empty-message">没有可用的MCP服务器</div>';
                return;
            }

            servers.forEach(server => {
                // 创建服务器项
                const serverItem = document.createElement('div');
                serverItem.className = 'server-item'; // 基本类
                serverItem.dataset.serverName = server.name;

                // 添加基于状态和禁用状态的CSS类
                serverItem.classList.add(`status-${server.status || 'disconnected'}`);
                if (server.disabled) {
                    serverItem.classList.add('disabled');
                }

                // 服务器连接状态
                let statusClass = server.status === 'connected' ? 'connected' :
                    (server.status === 'connecting' ? 'connecting' : 'disconnected');
                let statusTitle = server.status || 'disconnected';

                // 如果明确被禁用，覆盖状态显示
                if (server.disabled) {
                    statusClass = 'disabled';
                    statusTitle = '已禁用';
                }

                // 设置服务器项内容，添加滑块开关
                serverItem.innerHTML = `
                    <div class="server-status ${statusClass}" title="${statusTitle}"></div>
                    <div class="server-name">${server.name}</div>
                    <div class="server-actions">
                        <button class="icon-button delete-server" title="删除服务器">❌</button>
                        <label class="server-toggle" title="${server.disabled ? '启用服务器' : '禁用服务器'}">
                            <input type="checkbox" class="server-toggle-input" ${!server.disabled ? 'checked' : ''}>
                            <span class="server-slider"></span>
                        </label>
                    </div>
                `;

                // 服务器项点击事件：显示工具列表
                serverItem.addEventListener('click', (e) => {
                    // 忽略滑块和按钮区域的点击
                    if (!e.target.closest('.server-actions')) {
                        vscode.postMessage({
                            command: 'getServerTools',
                            serverName: server.name
                        });

                        // 更新选中状态
                        document.querySelectorAll('.server-item').forEach(item => {
                            item.classList.remove('selected');
                        });
                        serverItem.classList.add('selected');
                    }
                });

                // 删除服务器按钮
                const deleteBtn = serverItem.querySelector('.delete-server');
                if (deleteBtn) {
                    deleteBtn.addEventListener('click', (e) => {
                        e.stopPropagation();
                        console.log(`Delete button clicked for ${server.name}`); // 添加日志
                        // 直接发送删除命令，确认逻辑移到后端
                        vscode.postMessage({
                            command: 'deleteServer',
                            serverName: server.name
                        });
                    });
                }

                // 启用/禁用服务器滑块
                const toggleInput = serverItem.querySelector('.server-toggle-input');
                if (toggleInput) {
                    toggleInput.addEventListener('change', (e) => {
                        e.stopPropagation();
                        console.log('toggleServer', server.name, e.target.checked);
                        vscode.postMessage({
                            command: 'toggleServer',
                            serverName: server.name,
                            enable: e.target.checked
                        });
                    });
                }

                serversList.appendChild(serverItem);
            });

            // 默认选中第一个服务器
            if (servers.length > 0) {
                const firstServer = serversList.querySelector('.server-item');
                if (firstServer) {
                    firstServer.classList.add('selected');
                    vscode.postMessage({
                        command: 'getServerTools',
                        serverName: servers[0].name
                    });
                }
            }
        }

        // 工具列表更新函数
        function updateToolsList(serverName, tools) {
            const toolsList = document.getElementById('tools-list');
            if (!toolsList) return;

            // 清空工具列表
            toolsList.innerHTML = '';

            if (!tools || tools.length === 0) {
                toolsList.innerHTML = `<div class="empty-message">${serverName} 没有可用的工具</div>`;
                return;
            }

            // 添加工具组标题
            const groupTitle = document.createElement('div');
            groupTitle.className = 'tools-group-title';
            groupTitle.textContent = `${serverName} 可用工具 (${tools.length})`;
            toolsList.appendChild(groupTitle);

            // 添加工具批量控制按钮
            const controlsEl = document.createElement('div');
            controlsEl.className = 'tools-controls';
            controlsEl.innerHTML = `
                <button id="auto-approve-all" class="button small">全部自动批准</button>
                <button id="manual-approve-all" class="button small">全部手动批准</button>
            `;

            // 将按钮添加到标题行
            groupTitle.appendChild(controlsEl);

            // 添加自动批准全部按钮事件
            controlsEl.querySelector('#auto-approve-all').addEventListener('click', (e) => {
                e.stopPropagation(); // 防止触发标题行的其他事件
                const toolNames = tools.map(tool => tool.name);
                vscode.postMessage({
                    command: 'toggleToolAutoApprove',
                    serverName,
                    toolNames,
                    autoApprove: true
                });
            });

            // 添加手动批准全部按钮事件
            controlsEl.querySelector('#manual-approve-all').addEventListener('click', (e) => {
                e.stopPropagation(); // 防止触发标题行的其他事件
                const toolNames = tools.map(tool => tool.name);
                vscode.postMessage({
                    command: 'toggleToolAutoApprove',
                    serverName,
                    toolNames,
                    autoApprove: false
                });
            });

            tools.forEach(tool => {
                const toolItem = document.createElement('div');
                toolItem.className = 'tool-item';

                // 判断工具是否启用自动批准
                const autoApprove = tool.autoApprove === true;

                // 创建工具HTML
                let toolHTML = `
                    <div class="tool-icon">⚡</div>
                    <div class="tool-details">
                        <div class="tool-name">${tool.name}</div>
                        ${tool.description ? `<div class="tool-description">${tool.description}</div>` : ''}
                    </div>
                    <div class="tool-auto-approve ${autoApprove ? 'enabled' : 'disabled'}">
                        ${autoApprove ? '自动批准' : '手动批准'}
                    </div>
                `;
                console.log('tool', tool, 'tool.properties', tool.inputSchema.properties);
                // 添加工具参数悬浮提示
                if (tool.inputSchema.properties) {
                    const param = tool.inputSchema.properties;
                    let paramsHTML = `<div class="tool-params-tooltip">
                        <div class="params-title">参数信息：</div>`;

                    for (const [paramName, paramDetails] of Object.entries(param)) {
                        // 检查参数是否必填
                        const required = tool.inputSchema.required && tool.inputSchema.required.includes(paramName);
                        paramsHTML += `
                            <div class="param-item">
                                <span class="param-name">${paramName}</span>
                                <span class="param-type">${paramDetails.type || "any"}</span>
                                ${paramDetails.description ? `<div class="param-description">${paramDetails.description}</div>` : ''}
                                ${required ? '<div class="param-required">必填</div>' : ''}
                            </div>
                        `;
                    }

                    paramsHTML += `</div>`;
                    toolHTML += paramsHTML;
                }

                toolItem.innerHTML = toolHTML;

                // 添加点击事件：切换自动批准状态和添加到输入框
                toolItem.addEventListener('click', (e) => {
                    // 如果点击的是自动批准区域
                    if (e.target.closest('.tool-auto-approve')) {
                        // 切换工具自动批准状态
                        vscode.postMessage({
                            command: 'toggleToolAutoApprove',
                            serverName,
                            toolNames: [tool.name],
                            autoApprove: !autoApprove
                        });
                    } else {
                        // 否则，添加工具到输入框
                        const template = `<mcp-tool server="${serverName}" tool="${tool.name}" params={"param1": "value1"}></mcp-tool>`;
                        addToInput(template);
                        switchToChatView(); // 返回聊天视图
                        closeMcpToolsPopup(); // 关闭工具弹窗
                    }
                });

                toolsList.appendChild(toolItem);
            });
        }

        // 扩展消息处理程序，添加处理MCP消息的代码
        window.addEventListener('message', event => {
            const message = event.data;

            switch (message.command) {
                // ... existing code ...

                // MCP服务器列表更新 - 新命令名
                case 'mcpServersUpdated':
                    console.log('收到MCP服务器列表更新', message.servers);
                    
                    // 更新MCP管理界面的服务器列表(如果存在)
                    if (document.getElementById('servers-list')) {
                    updateServersList(message.servers);
                    }
                    
                    // 更新MCP工具弹窗的服务器列表
                    if (document.getElementById('mcp-servers-list') && mcpPopupVisible) {
                        updateMcpServers(message.servers);
                    }
                    break;

                // 处理服务器工具数据
                case 'serverToolsData':
                    console.log('接收到服务器工具数据:', message.serverName, message.tools?.length || 0);
                    
                    // 更新MCP管理界面的工具列表(如果存在)
                    if (document.getElementById('tools-list')) {
                    updateToolsList(message.serverName, message.tools);
                    }
                    
                    // 更新MCP工具弹窗的工具列表(如果可见)
                    if (document.getElementById('mcp-tools-list') && mcpPopupVisible) {
                        // 检查是否与当前选中的服务器匹配
                        if (message.serverName === currentlySelectedServerName) {
                    updateMcpTools({
                        serverName: message.serverName,
                        tools: message.tools || []
                    });
                        } else {
                            console.log(`工具弹窗：忽略非当前选中服务器 ${message.serverName} 的工具数据`);
                        }
                    }
                    break;

                // ... existing code ...
            }
        });
        // 确保在DOM加载完成后执行初始化函数
        document.addEventListener('DOMContentLoaded', () => {
            initUI();
            console.log('UI初始化完成');
        });

        // 以防DOMContentLoaded事件已经触发，立即尝试初始化
        if (document.readyState === 'interactive' || document.readyState === 'complete') {
            initUI();
            console.log('UI延迟初始化完成');
        }

        // 添加打开MCP设置按钮的事件处理
        document.getElementById('open-mcp-settings')?.addEventListener('click', () => {
            vscode.postMessage({
                command: 'openMcpSettings',
                action: 'openFile'
            });
        });
    </script>
</body>

</html>